Search code examples
pythonlistdictionarylocal

Merging different dictionaries together in one list


I have created 4 different sets of dictionaries with the guidance of this post: Python variables as keys to dict. I now want to merge all these dictionaries into 1 list. I tried the following:

classes = ['apple', 'orange', 'pear', 'mango']
class_dict = {}
store = []

for fruit in classes:
    if fruit == "orange":
        o = 2
        q = 1
    else:
        o = 0
        q = 0

    for j in ('fruit', 'o', 'q'):
        class_dict[j] = locals()[j]
    print (class_dict)
    store.append(class_dict)
print ("store: ", store)

The output is as shown below. As you can see, store only contains a list of the same dictionary being appended to it each time. I'm not sure where I'm going wrong and some help on this would be much appreciated!

{'fruit': 'apple', 'o': 0, 'q': 0}
{'fruit': 'orange', 'o': 2, 'q': 1}
{'fruit': 'pear', 'o': 0, 'q': 0}
{'fruit': 'mango', 'o': 0, 'q': 0}

store:  [{'fruit': 'mango', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}]

Solution

  • You need to move your class_dict inside the loop.

    classes = ['apple', 'orange', 'pear', 'mango']
    
    store = []
    
    for fruit in classes:
        class_dict = {}
        if fruit == "orange":
            o = 2
            q = 1
        else:
            o = 0
            q = 0
    
        for j in ('fruit', 'o', 'q'):
            class_dict[j] = locals()[j]
        print (class_dict)
        store.append(class_dict)
    print ("store: ", store)
    

    output:

    {'fruit': 'apple', 'o': 0, 'q': 0}
    {'fruit': 'orange', 'o': 2, 'q': 1}
    {'fruit': 'pear', 'o': 0, 'q': 0}
    {'fruit': 'mango', 'o': 0, 'q': 0}
    store:  [{'fruit': 'apple', 'o': 0, 'q': 0}, {'fruit': 'orange', 'o': 2, 'q': 1}, {'fruit': 'pear', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}]