简体   繁体   中英

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. 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? (As you have them, list_1 is a tuple and list_2 is a 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'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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