python - 使用 Python 在列表中查找匹配的字典对

标签 python loops dictionary

在给定列表中:

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/

相关文章:

python - 在外键中使用 Django bulk_create 对象?

perl - 如何在 Perl 的 for 循环中重命名文件

python - 列表中的嵌套字典

python - 如何使用 GoogleDrive 的 Python 快速入门循环遍历 nextPageToken

c - 即使使用命令 if(*str == 'stop' ) 并输入 stop,“While”循环也不会停止

python - 在 shelve 和 sqlite 之间选择真正大的字典(Python)

java - 如何在 JAVA 中检查 map 中存在的值

python - TypeError : NoneType, 相等则可以比较,大于则报错

Python ctypes 生成器

python - partial_dependence() 为 python 广义加法模型获得了意外的关键字参数 'feature'。我如何解决它?