在给定列表中:
unmatched_items_array = [{'c': 45}, {'c': 35}, {'d': 5}, {'a': 3.2}, {'a': 3}]
找到所有“键”对并打印出来,如果没有找到给定字典的对,则打印出该字典。
到目前为止,我设法写的东西是可行的,但它会继续测试列表中的某些项目,即使它们已经过测试。不确定如何修复它。
for i in range(len(unmatched_items_array)):
for j in range(i + 1, len(unmatched_items_array)):
# when keys are the same print matching dictionary pairs
if unmatched_items_array[i].keys() == unmatched_items_array[j].keys():
print(unmatched_items_array[i], unmatched_items_array[j])
break
# when no matching pairs print currently processed dictionary
print(unmatched_items_array[i])
输出:
{'c': 45} {'c': 35}
{'c': 45}
{'c': 35}
{'d': 5}
{'a': 3.2} {'a': 3}
{'a': 3.2}
{'a': 3}
输出应该是什么:
{'c': 45} {'c': 35}
{'d': 5}
{'a': 3.2} {'a': 3}
我在这里做错了什么?
最佳答案
使用 collections.defaultdict
例如:
from collections import defaultdict
unmatched_items_array = [{'c': 45}, {'c': 35}, {'d': 5}, {'a': 3.2}, {'a': 3}]
result = defaultdict(list)
for i in unmatched_items_array:
key, _ = i.items()[0]
result[key].append(i) #Group by key.
for _, v in result.items(): #print Result.
print(v)
输出:
[{'a': 3.2}, {'a': 3}]
[{'c': 45}, {'c': 35}]
[{'d': 5}]
关于python - 使用 Python 在列表中查找匹配的字典对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56972056/