Combine 2 lists of dictionaries based on matching values, otherwise keep original?

python merge dictionaries with same values
python merge list of dictionaries with same keys
write a python program to combine values in python list of dictionaries
python merge list of dictionaries by key
merge multiple dictionaries python
python merge dictionaries add values
python merge dictionaries with common keys
python dictionary sum values with same key

Is it possible to loop through the fruit list of dictionaries, and then lookup if it has a matching tree, and output the dictionary from the fruit with the height appended? I would also want to include the dictionary in the original form if there is no match. So the output in this scenario would be the combined list of dictionaries.

Desired output:

combined = [
    {'Type':'Tree', 'Name':'Pear', 'Color':'Red,Green', 'Height':'25ft'},
    {'Type':'Bush', 'Name':'Raspberry', 'Color':'Red,White'},
    {'Type':'Tree', 'Name':'Apple', 'Color':'Red,Green', 'Height':'15ft'}

Starting tables:

fruit = [
    {'Type':'Tree', 'Name':'Pear', 'Color':'Red,Green'},
    {'Type':'Bush', 'Name':'Raspberry', 'Color':'Red,White'},
    {'Type':'Tree', 'Name':'Apple', 'Color':'Red,Green'}

type = [
    {'Type':'Tree', 'Fruit':'Pear', 'Height':'25ft'},
    {'Type':'Tree', 'Fruit':'Apple', 'Height':'15ft'},
    {'Type':'Root', 'Fruit':'Carrot', 'Height':'2ft'}

When i try to do this, I keep getting duplicate outputs when using the following. I think it's because of the nested loops, but I'm not sure.

combined = []
for i in fruit:
    for x in type:
        if i['Name'] == x['Name']:
            out = i
            out['Height'] = x['Height']

The problem lies in the if-else statement inside your inner loop.

You should set a flag to check if there is a match inside your inner loop, if there is none, you should then add the current fruit outside the inner loop.

combined = []
for i in fruit:
    found = False
    for x in type:
        if i['Name'] == x['Fruit']:
            out = []
            out = i
            out['Height'] = x['Height']
            found = True
    if found == False:

Python, Given two list of dictionaries, the task is to merge these two lists of dictionaries based on some value. Method #1: Using defaultdict and extend to merge two list of dictionaries based on school_id. Method #2: Using extend() only. itemgetter · Ways to sort list of dictionaries by values in Python - Using lambda function  I'm combining two lists of dicts, based on the value of the key 'time'. Merging two lists of dicts based on the value of a specific key Search dictionary for

Python, Given two dictionary, the task is to combine the dictionaries such that we get the added values for common keys in resultant dictionary. Example: Input: dict1 for key in dict2: if key in dict1: dict2[key] = dict2[key] + dict1[key]. else : pass Method #2: Using collections. first_page Python | Find Min/Max in heterogeneous list. Perhaps, we could make generic keys, or maybe we would just truncate those remaining values. At any rate, keep those rules in the back of your mind. Solutions. As with most problems, merging two lists into a dictionary has many solutions. Let’s take a look at a few. Convert Two Lists with Zip and the Dict Constructor

If you are using Python 3.5+, using fruit and tree_type variables as you defined (type was renamed as tree_type to avoid conflit):

combined = [{**fruit_dict, 
             **next((type_dict for type_dict in tree_type if fruit_dict["Name"] == type_dict["Fruit"]), {})} 
            for fruit_dict in fruit]
Some explanation of this code:

The expression next((type_dict for type_dict in tree_type if fruit_dict["Name"] == type_dict["Fruit"]), {}) finds a type_dict inside tree_type that matchs fruit_dict and returns it, otherwise it return an empty dict {}.

The expression {**d1, **d2} is used to merge the two dictionaries. None of the dictionaries is altered in this expression, a new one is returned.

This code is not optimized when tree_type is a large list. If it is the case, you should organize this list in a different data structure, probably a dictionary.

For example:

tree_types_by_fruit = {type_dict["Fruit"]: type_dict for type_dict in tree_type}
combined = [{**fruit_dict, **tree_types_by_fruit.get(fruit_dict["Name"], {})} for fruit_dict in fruit]

How to Merge two or more Dictionaries in Python ? –, What if we want to merged the contents of 2 or dictionaries to a new dictionary ? Merge dictionaries and keep values of common keys in list'''. That is to say that you can use update() to merge two dictionaries if you are not interested in keeping the original version of the dictionary you need to update. By the original version here I mean retaining the value of the key. Merging Two Dictionaries in a Single Expression

Merging Two Dictionaries, merging two dictionaries, retaining the greatest value among # common keys dict1 , this is a correct algorithm for merging our two dictionaries based on max-​value. Using the original ordering, such a case would cause key not in merged to use of a inline if-else statement and iterable unpacking, which helps keep our  Sort the lists to see non-matching values more easily, if necessary. If your lists are large, you may need to sort them to put all the non-matching values together. The instructions in the substeps below will convert the formulas to values to avoid recalculation errors, and if your lists are large, will avoid a long recalculation time.

Python Tutorial: Dictionaries, Python programs or scripts without lists and dictionaries are nearly Associative arrays consist - like dictionaries of (key, value) pairs, such that each That's the reason, why the output of the city dictionary, doesn't reflect the "original ordering": dic = { [1,2,3]:"abc"} Traceback (most recent call last): File "<stdin>", line 1,  If True, do not use the index values on the concatenation axis. The resulting axis will be labeled 0, …, n - 1. This is useful if you are concatenating objects where the concatenation axis does not have meaningful indexing information. Note the index values on the other axes are still respected in the join. keys: sequence, default None. Construct hierarchical index using the passed keys as the outermost level.

PEP 584 -- Add Union Operators To dict, This PEP proposes adding merge (|) and update (|=) operators to the Further, ChainMaps wrap their underlying dicts, so writes to the ChainMap will modify the original dict: Key conflicts will be resolved by keeping the rightmost value. This is a cursory list based on a subset of whatever arbitrary  Collections - Documentation. Version: 2.1.2 Introduction. A test library providing keywords for handling lists and dictionaries. Collections is Robot Framework's standard library that provides a set of keywords for handling Python lists and dictionaries.

  • Nice and easy addition to what I already had. I don't know why I didn't think of that... I think @jpp solution would work too, but I won't go that route unless I run into performance issues. Thank you both!
  • It is not scalable to larger tree_type. It is ok for large fruit.