简体   繁体   English

通过将其与现有列表进行比较来更新嵌套字典值

[英]Update Nested Dictionary value by comparing it with existing list

How to make changes in nested dictionary value by comparing its key value with an existing list. 如何通过将其键值与现有列表进行比较来更改嵌套字典值。

Eg.: I have list name as common: 例如:我的列表名称是常见的:

common=['abc','def','xyz','etc']
mydict={'abc':{'a':10,'b':20,'c':10}, 'rat':{'r':10,'a':20,'t':10} , 'etc':{'e':10,'t':20,'c':50}}

Now I want to change the value of 'b' to 50 because it exists in mydict key value same as I want to change the value of 't' to 10 I don't want any changes in 'rat' because it does not exist in list common. 现在我想将'b'的值更改为50因为它存在于mydict键值中,因为我想将't'的值更改为10我不希望'rat'中的任何更改因为它不存在在列表中常见。

common=['abc','def','xyz','etc']

mydict={'abc':{'a':10,'b':20,'c':10}, 'rat':{'r':10,'a':20,'t':10} , 'etc':{'e':10,'t':20,'c':50}}

input: 输入:

common=['abc','def','xyz','etc']

mydict={'abc':{'a':10,'b':20,'c':10}, 'rat':{'r':10,'a':20,'t':10} , 'etc':{'e':10,'t':20,'c':50}}

expected output: 预期产量:

mynewdict={'abc':{'a':10,'b':'50,'c':10}, 'rat':{'r':10,'a':20,'t':10} , 'etc':{'e':10,'t':10,'c':50}}

You can use indexing into a nested dictionary and compare the values of its keys. 您可以将索引用于嵌套字典并比较其键的值。

common=['abc','def','xyz','etc']
mydict={'abc':{'a':10,'b':20,'c':10}, 'rat':{'r':10,'a':20,'t':10} , 'etc':{'e':10,'t':20,'c':50}}

for items in mydict:
    if items in common:
        inneritem= mydict[items]
        if 'b' in inneritem:
            inneritem['b']=50
        if 't' in inneritem:
            inneritem['t']=10

print(mydict)

You can do it with a comprehension for one update at a time. 您可以一次理解一个更新。 Multiple updates would make this approach quite cumbersome unless you don't mind adding the "t" key to sub-dictionaries that don't have it.: 除非你不介意将“t”键添加到没有它的子词典中,否则多次更新会使这种方法非常麻烦:

newdict={k:{**d,'t':10} if k in common and 't' in d else d for k,d in mydict.items()}

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

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