I have a dictionary of dictionaries as shown below:
dict_1 = {'a': {0: 'name_1', 1: 'name_2'}, 'b': {0: 23, 1: 53}}
and I would want it be in required format:
result = [{'a': 'name_1', 'b': 23}, {'a': 'name_2', 'b': 53}]
However, I get this in the following format with the code below:
l=[]
c={}
for k, v in d.items():
for i in v:
j=str(i)
j=j.replace(j, k)
c[j]=v[i]
print(c)
l.append(c)
The result is not of the required structure
[{'a': 'name_2', 'b': 53}, {'a': 'name_2', 'b': 53}]
Any help here would be highly appreciated. Thanks.
CodePudding user response:
Not sure how this would generalize, but you can try:
result = [dict(zip(dict_1, d2)) for d2 in
zip(*(d.values() for d in dict_1.values()))]
output: [{'a': 'name_1', 'b': 23}, {'a': 'name_2', 'b': 53}]
CodePudding user response:
If the keys are the same in the nested dictionaries, this should work
dict_1 = {'a': {0: 'name_1', 1: 'name_2'}, 'b': {0: 23, 1: 53}}
# iterate over the keys in the nested dictionaries
# and map values in the inner dictionaries to the outer keys
[{i: d[k] for i, d in dict_1.items()} for k in list(dict_1['a'])]
# [{'a': 'name_1', 'b': 23}, {'a': 'name_2', 'b': 53}]
CodePudding user response:
It looks like the innermost keys in dict_1 corresponds to the positions in the resulting list.
So, you can use a list comprehension to build up the new list of dictionaries. Set n to the size of the inner dict.
>>> pivots = list(dict_1) # The keys 'a' and 'b'
>>> n = 2
>>> [{k: dict_1[k][i] for k in pivots} for i in range(n)]
>>> [{'a': 'name_1', 'b': 23}, {'a': 'name_2', 'b': 53}]