python - 使用 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}
我在这里做错了什么?
解决方案
使用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}]
推荐阅读
- rust - 如何定义绑定到 rust 中特定特征的类型?
- sql - Perl DBD:在准备 sql-server 插入语句时,ODBC 抛出“不支持多次绑定命名参数”
- javascript - 在 JavaScript 中这个输入的输出顺序是什么?为什么?
- javascript - 我将如何在 selenium webdriver 中自动执行此操作?
- python - 获取 / 遍历 xml 文件 (.h5) 文件的树视图,直到使用 h5py 生成最终分支
- angular - 如何检查用户是否已登录。Angular 12.1.2
- reactjs - React typescript 将数组识别为对象
- java - 读取文件时 Scanner 和 hasNextLine() 的 Java 问题
- c# - 我被要求创建一个打印 pdf 文件的 Windows 服务,下面的代码在我在控制台应用程序上运行但不在服务上运行时有效
- python - 在 previus 完成后,Celery Django 运行定期任务。[django 芹菜节拍]