将词典条目检查到另一个词典,如果确定,则添加key:value pair 进入

2024-06-01 03:25:57 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两本字典:

dict1 = [{file:2015a, instrument:NES, gain:23}, {file:2015b, instrument:NES, gain:26}, {file:2015d, instrument:NES, gain:25}]

dict2=  [{file:2015a, instrument:NES, gain:3333}, {file:2015c, instrument:PS2, gain:26}, {file:2015d, instrument:NES, gain:4545}]

我想做的是从dict2中提取所有使用instrument=PS2的字典条目,并将它们放在dict1中,忽略dict2中的所有其他条目

或者只是创建一个新字典dict3,它包含dict1中的所有条目nstrument:NES and dict2中所有的条目nstrument:PS2.

最简单的方法是什么


Tags: and方法字典条目filegaininstrumentnes
3条回答

这些是列表,字典是它们的元素

假设,如果键instrument的值为PS2,则希望将字典从dict2附加到dict1

for d in dict2:
    if d.get('instrument') == 'PS2':
        dict1.append(d)

另一方面,dict[1-2]不是列表的好名字

示例:

In [153]: dict1 = [{'file': '2015a', 'instrument': 'NES', 'gain': '23'}, {'file': '2015b', 'instrument': 'NES', 'gain': 26}, {'file': '2015d', 'instrument': 'NES', 'gain': 25}]

In [154]: dict2=  [{'file': '2015a', 'instrument': 'NES', 'gain': 3333}, {'file': '2015c', 'instrument': 'PS2', 'gain': 26}, {'file': '2015d', 'instrument': 'NES', 'gain': 4545}]

In [155]: for d in dict2:
   .....:     if d.get('instrument') == 'PS2':
   .....:         dict1.append(d)
   .....:         

In [156]: dict1
Out[156]: 
[{'file': '2015a', 'gain': '23', 'instrument': 'NES'},
 {'file': '2015b', 'gain': 26, 'instrument': 'NES'},
 {'file': '2015d', 'gain': 25, 'instrument': 'NES'},
 {'file': '2015c', 'gain': 26, 'instrument': 'PS2'}]

除上述答案外,您还可以:

tmp_lst = [i for i in dict2 for k,v in i.items() if (k,v)== ('instrument','PS2')]
print dict1+tmp_lst

会回来的

[{'instrument': 'NES', 'gain': '23', 'file': '2015a'}, {'instrument': 'NES', 'gain': '26', 'file': '2015b'}, {'instrument': 'NES', 'gain': '25', 'file': '2015d'}, {'instrument': 'PS2', 'gain': 26, 'file': '2015c'}]

它们是列表中的词典

>>> dict1=[{'file':'2015a', 'instrument':'NES', 'gain':23}, {'file':'2015b', 'instrument':'NES', 'gain':26}, {'file':'2015d', 'instrument':'NES', 'gain':25}]
>>> dict2=[{'file':'2015a', 'instrument':'NES', 'gain':3333}, {'file':'2015c', 'instrument':'PS2', 'gain':26}, {'file':'2015d', 'instrument':'NES', 'gain':4545}]

您可以对每个列表使用filter()并对其进行合并,以获得如下最终输出:

>>> list(filter(lambda x:x['instrument']=='NES', dict1))+list(filter(lambda x:x['instrument']=='PS2', dict2))
[{'instrument': 'NES', 'gain': 23, 'file': '2015a'}, {'instrument': 'NES', 'gain': 26, 'file': '2015b'}, {'instrument': 'NES', 'gain': 25, 'file': '2015d'}, {'instrument': 'PS2', 'gain': 26, 'file': '2015c'}]
>>> 

以下是各个输出:

>>> list(filter(lambda x:x['instrument']=='NES', dict1))
[{'instrument': 'NES', 'gain': 23, 'file': '2015a'}, {'instrument': 'NES', 'gain': 26, 'file': '2015b'}, {'instrument': 'NES', 'gain': 25, 'file': '2015d'}]
>>> list(filter(lambda x:x['instrument']=='PS2', dict2))
[{'instrument': 'PS2', 'gain': 26, 'file': '2015c'}]

相关问题 更多 >