[英]How to change values in a nested dictionary
I need to change values in a nested dictionary. 我需要更改嵌套字典中的值。 Consider this dictionary:
考虑一下这个字典:
stocks = {
'name': 'stocks',
'IBM': 146.48,
'MSFT': 44.11,
'CSCO': 25.54,
'micro': {'name': 'micro', 'age': 1}
}
I need to loop through all the keys and change the values of all the name
keys. 我需要遍历所有键并更改所有
name
键的值。
stocks.name
stocks.micro.name
These keys need to be changed. 这些键需要更改。 But, I will not know which keys to change before hand.
但是,我不知道要先更改哪些键。 So, I'll need to loop through keys and change the values.
因此,我需要遍历键并更改值。
Example 例
change_keys("name", "test")
Output 产量
{
'name': 'test',
'IBM': 146.48,
'MSFT': 44.11,
'CSCO': 25.54,
'micro': {'name': 'test', 'age': 1}
}
def changeKeys(d, repl):
for k,v in zip(d.keys(),d.values()):
if isinstance(v, dict):
changeKeys(v,repl)
elif k == "name":
d[k]= repl
A recursive solution that supports unknown number of nesting levels: 支持未知数量的嵌套级别的递归解决方案:
def change_key(d, required_key, new_value):
for k, v in d.items():
if isinstance(v, dict):
change_key(v, required_key, new_value)
if k == required_key:
d[k] = new_value
stocks = {
'name': 'stocks',
'IBM': 146.48,
'MSFT': 44.11,
'CSCO': 25.54,
'micro': {'name': 'micro', 'age': 1}
}
change_key(stocks, 'name', 'new_value')
print(stocks)
# {'name': 'new_value',
# 'MSFT': 44.11,
# 'CSCO': 25.54,
# 'IBM': 146.48,
# 'micro': {'name': 'new_value',
# 'age': 1}
# }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.