0

I have a with dict with the following format

dic = {
          'x':[1, 2, 3, 4], 
          'y':[2, 4, 5, 6], 
          'z':['a', 'b', 'c', 'g'],
          'a':['d', 'e', 'f', 'a'], 
}

I want to convert it to below format

lst_wth_dic = [

               {'x':1, 'y':2, 'z': 'a', 'a':'d'}, 
               {'x':2, 'y':4, 'z':'b', 'a':'e'},
               {'x':3, 'y':5, 'z':'c', 'a': 'f'}, 
               {'x':4, 'y':6, 'z':'g', 'a': 'a'}
]

What I have tried so far is this

import copy
lst_wth_dic = []
b = {}
for key, val in dic.items():
     for item in val:
             b[key] = item
     c = copy.copy(b)
     lst_wth_dic.append(c)

It does not achive the desired output that i require.

wwii
  • 23,232
  • 7
  • 37
  • 77
YASIR KHAN
  • 11
  • 2

2 Answers2

2

You could do:

d = {
          'x':[1, 2, 3, 4],
          'y':[2, 4, 5, 6],
          'z':['a', 'b', 'c', 'g'],
          'a':['d', 'e', 'f', 'a'],
}

lst_dic = [dict(zip(d.keys(), vs)) for vs in zip(*d.values())]

print(lst_dic)

Output

[{'a': 'd', 'x': 1, 'y': 2, 'z': 'a'},
 {'a': 'e', 'x': 2, 'y': 4, 'z': 'b'},
 {'a': 'f', 'x': 3, 'y': 5, 'z': 'c'},
 {'a': 'a', 'x': 4, 'y': 6, 'z': 'g'}]

The expression:

zip(*d.values())

creates the following iterable:

[(1, 2, 'a', 'd'), (2, 4, 'b', 'e'), (3, 5, 'c', 'f'), (4, 6, 'g', 'a')]

then for each of those tuples zip it with the keys of d. The above list comprehension is equivalent to the following for loop:

lst_dic = []
for vs in zip(*d.values()):
    lst_dic.append(dict(zip(d.keys(), vs)))
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0

You could do dict comprehensions within a list comprehension:

   lst_wth_dic = [{k:v[i] for k, v in dic.items()} for i in range(4)]
Billy
  • 5,179
  • 2
  • 27
  • 53