我正在尝试获取 first_list
和 second_list
中常见的键值,如下所示,first_list
和 second_list
有 X
和 Z
作为公共(public)键,我想得到 X
和 Z
对应的值并创建一个最终字典,如 EXPECTED OUTPUT BELOW
所示,我有当前和预期的输出,有人可以就这里的错误提供指导吗?
first_list = [{'W':['xyz','abc','def']},{'X':['1','2','3']},{'Y':['4','5','6']},{'Z':['1','5','7']}]
second_list = [{'X':True},{'Z':True}]
first_list_keys,second_list_keys = [],[]
for item in first_list:
for key,value in item.items():
print (key,value)
first_list_keys.append(key)
for item in second_list:
for key,value in item.items():
print (key,value)
second_list_keys.append(key)
print(first_list_keys,second_list_keys)
c = set(first_list_keys).intersection(second_list_keys)
print (c)
final_dict = {}
for item in c:
item_dict = {}
for data in first_list:
for key,value in data.items():
print (key,value)
if key == item:
print ('==================')
print (value)
item_dict['deps'] = value
for item in c:
for data in second_list:
for key,value in data.items():
print (key,value)
if key == item:
print ('==================')
print (value)
item_dict['values'] = True
final_dict[key] = item_dict
print (final_dict)
当前输出:-
{'Z': {'deps': ['1', '5', '7'], 'values': True}}
预期输出:-
{'X':{"deps":['1','2','3'],"values": true },'Z':{"deps":['1','5','7'],"values": true }
更新:-
{'W':{"deps":['xyz','abc','def'],"values": False},'X':{"deps":['1','2','3'],"values": True },'Y':{"deps":['4','5','6'],"values":False},'Z':{"deps":['1','5','7'],"values": True }
最佳答案
这是一种解决方案。请注意,为了能够在第二个列表中查找键,我首先将其转换为字典,然后使用它。此代码假定任一列表中的每个字典都只包含一个键/值对:
first_list = [{'W':['xyz','abc','def']},{'X':['1','2','3']},{'Y':['4','5','6']},{'Z':['1','5','7']}]
second_list = [{'X':True},{'Z':True}]
result ={}
# Create a map from "second_list", where for each entry in "second_list", we pull out the one
# key/value pair contained therin and then add it to the new dictionary
second_list_map = { next(iter(kv.keys())):next(iter(kv.values())) for kv in second_list}
# For each entry in the first list...
for fentry in first_list:
# Get the one key in the entry
key = next(iter(fentry.keys()))
# If this key is also in the second list...
if key in second_list_map:
# Add the appropriate entry to the result dictionary
result[key] = {
"deps": fentry[key],
"values": second_list_map[key]
}
print(result)
结果:
{'X': {'deps': ['1', '2', '3'], 'values': True}, 'Z': {'deps': ['1', '5', '7'], 'values': True}}
这是更新要求的主体,保留第一个列表中的所有值,并注意第二个列表中缺少带有 'values': False
的键:
for fentry in first_list:
key = next(iter(fentry.keys()))
result[key] = {
"deps": fentry[key],
"values": second_list_map[key] if key in second_list_map else False
}
结果:
{'W': {'deps': ['xyz', 'abc', 'def'], 'values': False}, 'X': {'deps': ['1', '2', '3'], 'values': True}, 'Y': {'deps': ['4', '5', '6'], 'values': False}, 'Z': {'deps': ['1', '5', '7'], 'values': True}}
关于python - 如何获取两个列表之间普遍存在的键值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66253585/