[英]Python: Combine Two Lists of Dictionaries on Common Value
我有兩個字典列表。 我希望工會基於
list_1 = ({'foo': 'bar', 'ip': '1.2.3.4'}, {'foo': 'bar2', 'ip': '2.3.4.5'})
list_2 = ({'foo': 'bar3', 'ip': '1.2.3.4'})
#calculated
list_3 should be: ({'foo': 'bar3', 'ip': '1.2.3.4'})
我正在努力:
tmplist = list(item['ip'] for item in list_1
if item['ip'] in list_2)
編輯:我有嵌套的 for 循環。 有沒有更蟒蛇的方式?
for item1 in list1:
print(item1['ip_address'])
for item2 in list2:
if item1['ip_address'] == item2['ip_address']:
print("Got a match: " + item1['foo'] + " == " +item2['foo'])
我已經更正了您問題的價值和格式(希望沒問題)。 使用下面的方法,您可以找到字典列表之間的共同值。
list_1 = [{'foo': 'bar', 'ip': '1.2.3.4'}, {'foo': 'bar2', 'ip': '2.3.4.5'}]
list_2 = [{'foo': 'bar', 'ip': '1.2.3.4'}]
y0_tupleset = set(tuple(sorted(d.items())) for d in list_1)
y1_tupleset = set(tuple(sorted(d.items())) for d in list_2)
y_inter = y0_tupleset.intersection(y1_tupleset)
y_inter_dictlist = [dict(it) for it in list(y_inter)]
print(y_inter_dictlist)
我想您的意思是list_1
和list_2
在您的問題中是...列表,對嗎? (當你擁有它們時, list_1
是一個tuple
,而list_2
是一個dict
。
如果是這種情況,那么在聲明列表時必須使用方括號[]
而不是括號()
。
list_1 = [{'foo': 'bar', 'ip': '1.2.3.4'}, {'foo': 'bar2', 'ip': '2.3.4.5'}]
list_2 = [{'foo': 'bar3', 'ip': '1.2.3.4'}]
好的,假設你可以有這樣的實現:
def matchings(iter1, iter2, selector):
keys = {*map(selector, iter1)}
return [*filter(lambda e: selector(e) in keys, iter2)]
並像這樣使用它:
matchings(list_1, list_2, lambda e: e['ip'])
# [{'foo': 'bar3', 'ip': '1.2.3.4'}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.