-3

I have loaded a YAML file (template) that I want to modify (keys and some values).

e.g.

key_to_rename:
  a: "1"
  b: "2"
  c: "3"

How do I find & rename a key with PyYAML?

  my_dict = yaml.load(stream)

  for key, value in my_dict.iteritems():
     if (key == "key_to_rename"):
       print key
       key = "new_name"
       print key

  print yaml.dump(my_dict)

but that's still not persisting the change

zabumba
  • 12,172
  • 16
  • 72
  • 129
  • I have loaded the YAML indeed, but I can't find out how to rename the key. The input comes from a file, so I could replace the string in the file, but I figured it would be more elegant if I could do that on the yaml dict. (Stefano, I hope you are not the -1) – zabumba Jun 09 '14 at 13:15
  • How helpful it is to close a question?? Seriously guys!!? Give me hint at least? – zabumba Jun 09 '14 at 13:22
  • 1
    `my_dict["new_name"] = value` then `my_dict.pop(key, None)` – Mansueli Jun 09 '14 at 14:03
  • Got it! Thanks mate. Note that I am both new to python and pyyaml (just started today). It is appreciated that someone actually tried to help instead of trying to close the question. – zabumba Jun 09 '14 at 14:10

1 Answers1

0

Thanks to Kyllopardiun

  stream = open("./tiny.yml", 'r')
  my_dict = yaml.load(stream)

  # First make a copy with a new name
  my_dict["new_name"] = qb_dict['key_to_rename'] 

  # Then remove the old key
  my_dict.pop("key_to_rename", None)
zabumba
  • 12,172
  • 16
  • 72
  • 129