首页 > 解决方案 > 使用 Python 在列表中查找匹配的字典对

问题描述

在给定的列表中:

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}

我在这里做错了什么?

标签: pythonloopsdictionary

解决方案


使用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}]

推荐阅读