我有2个字典,这是字典:
a = [{'filtered':'eat','lang':'en'},{'filtered':'drink','lang':'en'},{'filtered':'makan','lang':'id'},{'filtered':'minum','lang':'id'}]
b = [{'filtered':'drink','lang':'en'},{'filtered':'makan','lang':'id'},{'filtered':'tidur','lang':'id'}]
我想将这两个字典与'filtered'值相交作为过滤变量,我希望结果像这样:
result = [{'filtered':'drink','lang':'en'},{'filtered':'makan','lang':'id'}]
像这样在列表中与字典相交的代码是什么?谢谢您的回复。
答案 0 :(得分:0)
简单地:
>>> [v for v in a if v in b]
[{'filtered': 'drink', 'lang': 'en'}, {'filtered': 'makan', 'lang': 'id'}]
请注意,这是一个O(N ^ 2)操作,但由于dict在Python中不可哈希,因此加快操作速度并非易事。