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}}