Search code examples
pythondictionarylambdasequences

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.


Solution

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