Append dictionary in a for loop

Question:

I would like to append dictionary in a for loop such that i get a concatenated dictionary. Also, it is not necessary that keys of all dictionary will be exactly same.

For eq

 one={'a': '2', 'c': 't', 'b': '4'}
 two={'a': '3.4', 'c': '7.6'}
 three={'a': 1.2, 'c': 3.4, 'd': '2.3'}

Output:

combined={'a':['2','3.4','1.2'],'b':'4','c':['t','7.6','3.4'],
                'd':'2.3'}

Now coming to original question:

Every time a for loop iterates, a dictionary will be generated and i would like to append it.

Something like:

 emptydict={}

   for x in z:
      newdict=x.dict()
      emptydict.append(newdict)
      print(emptydict)
Asked By: Venkatesh Malhotra

||

Answers:

You can try something like this.

one = {'a': '2', 'c': 't', 'b': '4'}
two = {'a': '3.4', 'c': '7.6'}
three = {'a': 1.2, 'c': 3.4, 'd': '2.3'}

new_dict = {}
list_dict = [one, two, three]

for d in list_dict:
    for key in d:
        if key not in new_dict:
            new_dict[key] = []
        new_dict[key].append(d[key])

print(new_dict)

Output : {'a': ['2', '3.4', 1.2], 'c': ['t', '7.6', 3.4], 'b': ['4'], 'd': ['2.3']}

Answered By: bumblebee

You can try dict-comprehension and list-comprehension :

new_dict = {k : [j[k] for j in [one,two,three] if k in j] for k in set(list(one.keys())+list(two.keys())+list(three.keys())
# Output : { 'a': ['2', '3.4', 1.2], 'b': ['4'], 'c': ['t', '7.6', 3.4], 'd': ['2.3']}

If you want the keys with only one element as possible value not in the list then try this :

new_dict =  a = {k : [j[k] for j in [one,two,three] if k in j][0] if len([j[k] for j in [one,two,three] if k in j]) ==1 else [j[k] for j in [one,two,three] if k in j] for k in set(list(one.keys())+list(two.keys())+list(three.keys()))}
# Output : {'a': ['2', '3.4', 1.2], 'b': '4', 'c': ['t', '7.6', 3.4], 'd': '2.3'}

try this

 one={'a': '2', 'c': 't', 'b': '4'}
 two={'a': '3.4', 'c': '7.6'}
 three={'a': 1.2, 'c': 3.4, 'd': '2.3'}

df = pd.DataFrame([one,two,three])

     a    b    c    d
0    2    4    t  NaN
1  3.4  NaN  7.6  NaN
2  1.2  NaN  3.4  2.3

df.to_dict(orient='list')

Output

{'a': ['2', '3.4', 1.2],
 'b': ['4', nan, nan],
 'c': ['t', '7.6', 3.4],
 'd': [nan, nan, '2.3']}
Answered By: iamklaus

I have used your examples to do so –

one = {'a': '2', 'c': 't', 'b': '4'}
two = {'a': '3.4', 'c': '7.6'}
three = {'a': 1.2, 'c': 3.4, 'd': '2.3'}
dicts = [one, two, three]
for dictionary in dicts:
    for key, value in dictionary.items():
        try:
            new[key].append(value)
        except KeyError:
            new[key] = [value]

O/P –

{'a': ['2', '3.4', 1.2], 'c': ['t', '7.6', 3.4], 'b': ['4'], 'd': ['2.3']}
Answered By: Sushant