简体   繁体   English

Python:组合两个字典的公共值列表

[英]Python: Combine Two Lists of Dictionaries on Common Value

I have two lists of dictionaries.我有两个字典列表。 I want the union based on我希望工会基于

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'})

I'm trying:我正在努力:

tmplist = list(item['ip'] for item in list_1
                   if item['ip'] in list_2)

Edit: I have it with nested for loops.编辑:我有嵌套的 for 循环。 Is there a more pythonic way?有没有更蟒蛇的方式?

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'])

I have corrected value & format of your question(Hope it's OK).我已经更正了您问题的价值和格式(希望没问题)。 using below method you can find common values between list of dictionaries.使用下面的方法,您可以找到字典列表之间的共同值。

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)

I suppose you meant list_1 and list_2 in your questions to be... lists, right?我想您的意思是list_1list_2在您的问题中是...列表,对吗? (As you have them, list_1 is a tuple and list_2 is a dict . (当你拥有它们时, list_1是一个tuple ,而list_2是一个dict

If that is the case, then you have to use square brackets [] instead of parenthesis () when declaring your lists.如果是这种情况,那么在声明列表时必须使用方括号[]而不是括号()

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'}]

Ok, assuming that, you could have an implementation like this:好的,假设你可以有这样的实现:

def matchings(iter1, iter2, selector):
    keys = {*map(selector, iter1)}
    return [*filter(lambda e: selector(e) in keys, iter2)]

And use it like this:并像这样使用它:

matchings(list_1, list_2, lambda e: e['ip'])
# [{'foo': 'bar3', 'ip': '1.2.3.4'}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM