-2

so given a list of dictionaries:

    my_dict= [{'a': '4', 'b': '5', 'c': '1', 'd': '3'},  
              {'a': '1', 'b': '8', 'c': '1', 'd': '2'},
              {'a': '7', 'b': '4', 'c': '1', 'd': '5'}]

and a list of keys in the dictionary for example [ 'a', 'b'] I am trying to make a list of dictionaries for both 'a' and 'b' for their respective values i.e the final product will resemble

    new_dict = ['a':['4', '1', '7'], 'b':['5', '8', '4']]

any help will be appreciated

Guriqbal Chouhan
  • 49
  • 1
  • 1
  • 5

1 Answers1

1

Using collections

Demo:

import collections
d = collections.defaultdict(list)
my_dict= [{'a': '4', 'b': '5', 'c': '1', 'd': '3'}, {'a': '1', 'b': '8', 'c': '1', 'd': '2'}, {'a': '7', 'b': '4', 'c': '1', 'd': '5'}]
for i in my_dict:
    for k,v in i.items():
        d[k].append(v)
print( d )

Output:

defaultdict(<type 'list'>, {'a': ['4', '1', '7'], 'c': ['1', '1', '1'], 'b': ['5', '8', '4'], 'd': ['3', '2', '5']})
Rakesh
  • 81,458
  • 17
  • 76
  • 113