简体   繁体   English

如何更改嵌套字典的键

[英]How to change the key of a nested dictionary

How can I change the key of one nested dictionary?如何更改一个嵌套字典的键?

For example, how can I change data1 's "yes" into "no" below:例如,如何将下面的data1"yes"更改为"no"

dc = {'data1': {'yes': 'abc'}, 'data2': {'yes': 'xyz'}}
# CODES to get the result below:
dc = {'data1': {'no': 'abc'}, 'data2': {'yes': 'xyz'}}

dc[data1] = 'no'  # won't work.

Any help will be appreciated!任何帮助将不胜感激!

To change a single dictionary just reference the dictionary you want to change.要更改单个字典,只需引用您要更改的字典。

>>> d = {'data1': {'yes': 'abc'}, 'data2': {'yes': 'xyz'}}
>>> d['data1']['no'] = d['data1'].pop('yes')
>>> d
{'data2': {'yes': 'xyz'}, 'data1': {'no': 'abc'}}

And if you want to change yes entries across all the dicts you have to a loop over dict.values .如果您想更改所有字典中的yes条目,您必须遍历dict.values

>>> d = {'data1': {'yes': 'abc'}, 'data2': {'yes': 'xyz'}}
>>> for nested_d in d.values():
...     nested_d['no'] = nested_d.pop('yes')
...
>>> d
{'data1': {'no': 'abc'}, 'data2': {'no': 'xyz'}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM