0

I have a dict like

{'1': {'b': 1, 'c': 2}, '2': {'b': 3, 't': 4}, '3': {'b': 1, 'z': 1}}

and I need to replace all 'b' keys with, for example, 'bb' (and get a new dict). The output should be

{'1': {'bb': 1, 'c': 2}, '2': {'bb': 3, 't': 4}, '3': {'bb': 1, 'z': 1}}

Is there any easy-pythonic way to do this?

Thanks in advance.

alexvassel
  • 10,600
  • 2
  • 29
  • 31

1 Answers1

4

Like this:

In [3]: for k, v in d.items():
   ...:     d[k]['bb'] = v.pop('b')
   ...:     

In [4]: d
Out[4]: {'2': {'t': 4, 'bb': 3}, '3': {'z': 1, 'bb': 1}, '1': {'bb': 1, 'c': 2}}

The above code causes KeyError if some of the nested dictionaries don't have 'b' key. Fail-safe version:

In [8]: for k, v in d.items():
   ...:     if 'b' in v:
   ...:         d[k]['bb'] = v.pop('b')

The above solution will make changes to the original dictionary. You can make its copy with copy.deepcopy (like Padraic Cunningham suggested in comments).

One-liner (dictionary comprehension creates a new dict object):

In [13]: { x: dict(('bb' if y == 'b' else y, d[x][y]) for y in d[x]) for x in d }
Out[13]: {'2': {'t': 4, 'bb': 3}, '3': {'z': 1, 'bb': 1}, '1': {'bb': 1, 'c': 2}}
vaultah
  • 44,105
  • 12
  • 114
  • 143