如果与列表中每个字典中的一个键的值匹配,则将具有不同词典值的新键添加到词典列表中

时间:2018-12-13 23:30:48

标签: python dictionary

如果词典列表中的某些值作为dict1中的键,则在词典列表中创建一个新的键值对。

 dict1 = {4380: [{'name': 'john', 'age': 26}], 3450: [{'name': 'sam', 'age': 57}], 7150: [{'name': 'Tom', 'age': 36}]}

下面的字典列表

listofdict = [{'department': 3490, 'floor': 1}, {'department': 4380, 'floor': 5}, {'department': 7150, 'floor': 7}, {'department': 7160, 'floor': 8}]

我做了以下分配工作

for element in listofdict :
    if element['department'] in dict1.keys():
        element['Attributes'] = dict1[element['department']] 

这是我得到的输出

output = [{'department': 3490, 'floor': 1}, {'department': 4380, 'floor': 5, 'Attributes':[{'name': 'john', 'age': 26}]},
          {'department': 7150, 'floor': 7,'Attributes':[{'name': 'Tom', 'age': 36}]},{'department': 7160, 'floor': 8}]

但是我想从最终输出中删除不在dict1中的字典。

预期输出:

 output = [{'department': 4380, 'floor': 5, 'Attributes':[{'name': 'john', 'age': 26}]},{'department': 7150, 'floor': 7,'Attributes': [{'name': 'Tom', 'age': 36}]}]

我要避免列表中的字典与字典中带有字典1的键的字典中每个字典中一个键的值不匹配

1 个答案:

答案 0 :(得分:0)

将输出复制到新列表(省略不需要的部分):

dict1 = {4380: [{'name': 'john', 'age': 26}], 3450: [{'name': 'sam', 'age': 57}], 7150: [{'name': 'Tom', 'age': 36}]}

listofdict = [{'department': 3490, 'floor': 1}, {'department': 4380, 'floor': 5}, {'department': 7150, 'floor': 7}, {'department': 7160, 'floor': 8}]


output = []

for element in listofdict :
    if element['department'] in dict1.keys():
        element['Attributes'] = dict1[element['department']][0]
        output.append(element)


print(output)

dict1listofdict的原始问题数据结构中,您的代码与代码不匹配,因此代码进行了调整。

提示:执行完这段代码后,listofdictoutput可能会共享一些字典对象(更改字典中的内容会影响两者的内容),因此listofdict不应再使用。

相关问题