2个字典列表的Python交集

标签 python python-3.4

我有 2 个像这样的字典列表

list1 = [{'count': 351, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'},
     {'count': 332, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'},
     {'count': 336, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'},
     {'count': 359, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'},
     {'count': 309, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}]


list2 = [{'count': 359, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'},
     {'count': 351, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'},
     {'count': 381, 'evt_datetime': datetime.datetime(2015, 10, 22, 8, 45), 'att_value': 'red'}]

我正在尝试从两个列表中获取常见的指令。我希望输出与字典的键和值完全匹配。

[{'count': 359, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'},
     {'count': 351, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}]

这可以由 python 本身有效地完成还是需要像 pandas 一样的库?

最佳答案

使用列表理解:

[x for x in list1 if x in list2]

这会返回您的数据列表:

[{'count': 351, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}, {'count': 359, 'evt_datetime': datetime.datetime(2015, 10, 23, 8, 45), 'att_value': 'red'}]

关于2个字典列表的Python交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33542997/

相关文章:

python - 我无法创建适用于 "dev_appserver.py."的 Google Cloud Storage 文件

python map异常继续映射执行

Python 3.4并发.futures.Executor不提供暂停和恢复线程的控制

python - Protobuf-2.6.0 与 Python 3?

pyqt4 - 名称 unicode 未定义 python3

Python 3.4 - 将字符串输入格式化为标题格式

python - 如何居中对齐 numpy.savetxt 生成的文本?

python - Google App Engine - 连接到 MySql 数据库 - 意外的关键字参数 'user'

Python random.seed 表现异常

python - pymongo 在尝试连接到本地 Mongo 实例时返回 SSL 错误