简体   繁体   中英

How to combine data from two sequences of dictionaries

I have two lists:

list1 = [{'tag':'XXX', 'key1':'a'}, {'tag':'YYY', 'key1':'a'}]

list2 = [{'tag':'XXX', 'key1':'c'}, {'tag':'ZZZ', 'key1':'d'}]

I need to build a new list:

 comblist = [{'tag':'XXX', 'key1':'a'}, {'tag':'YYY', 'key1':'a'}, {'tag':'ZZZ', 'key1':'d'}]

I need to add elements from list2 to list1, but only that for which value of key 'tag' isn't present in values of key 'tag' in list1.

You could first create a set of tag values from list1 and then use a comprehension to extend list1 by dictionaries in list 2 which have new tags:

>>> list1 = [{'tag':'XXX', 'key1':'a'}, {'tag':'YYY', 'key1':'a'}]
>>> list2 = [{'tag':'XXX', 'key1':'c'}, {'tag':'ZZZ', 'key1':'d'}]
>>> tags = set(d['tag'] for d in list1)
>>> list1.extend(d for d in list2 if not d['tag'] in tags)
>>> list1
[{'key1': 'a', 'tag': 'XXX'}, {'key1': 'a', 'tag': 'YYY'}, {'key1': 'd', 'tag': 'ZZZ'}]

You can do it more simple using update method of dictionary:

dict1 = dict((x['tag'], x['key1']) for x in list1)
dict2 = dict((x['tag'], x['key1']) for x in list2)

result = dict2.copy()
result.update(dict1)

result = [{'tag': key, 'key1': value} for key, value in result.iteritems()]

So i built function:

def add(seq1, seq2, key=None):
seen = set()
#add values from seq1 for selected key (or keys) to seen.
for item in seq1:
    seen.add(key(item))
# Check if value(s) for selected key(s) is in seen.   
for item in seq2:
    # if statemant added for support two types of sequences lists end dicts
    val = item if key is None else key(item)
    if val not in seen:
        # Add selected element from seq2 to seq1 and value of key to seen
        seq1.append(item)
        seen.add(val)
return seq1

and call it:

comblist = list(add(list1, list2, key=lambda d: d['tag']))

It work good. Function is suitable for different kinds of data structures and properties. I'm not pro and i'm curious. Is there any easier or faster way? My lists consist of over 1500 dictionaries, and each dict has 15 key, value pairs.

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