Convert Dictionary String Values to List of Dictionaries - Python
We are given a dictionary where the values are strings containing delimiter-separated values and the task is to split each string into separate values and convert them into a list of dictionaries, with each dictionary containing a key-value pair for each separated value. For example: consider this dictionary {"Gfg": "1:2:3", "best": "4:8:11"} then the output should be [{'Gfg': '1', 'best': '4'}, {'Gfg': '2', 'best': '8'}, {'Gfg': '3', 'best': '11'}].
Using zip() and split()
We can first split the values in the dictionary using split(':') and then use zip() to pair corresponding elements from all lists.
d = {"Gfg": "1:2:3", "best": "4:8:11"}
# Splitting values and using zip to pair corresponding elements
res = [dict(zip(d.keys(), vals)) for vals in zip(*[v.split(':') for v in d.values()])]
print(res)
Output
[{'Gfg': '1', 'best': '4'}, {'Gfg': '2', 'best': '8'}, {'Gfg': '3', 'best': '11'}]
Explanation:
- We use split(':') to break each string into a list of values.
- zip(*[v.split(':') for v in d.values()]) transposes these lists thus pairing corresponding elements together.
- dict(zip(d.keys(), vals)) creates a dictionary for each paired group hence, final result is a list of dictionaries.
Using enumerate and split()
This method uses a loop to iterate through the dictionary and splits the string values by the : delimiter and then each split value is assigned to a separate dictionary. The result is a list of dictionaries where each dictionary contains key-value pairs corresponding to the split values.
from collections import defaultdict
d1 = {"Gfg": "1:2:3", "best": "4:8:11"}
d2 = defaultdict(dict)
for k in d1:
for i, v in enumerate(d1[k].split(':')):
d2[i][k] = v
r = [d2[i] for i in d2]
print(r)
Output
[{'Gfg': '1', 'best': '4'}, {'Gfg': '2', 'best': '8'}, {'Gfg': '3', 'best': '11'}]
Explanation:
- dictionary d is iterated using a loop that splits each string by : and maps the results to temporary dictionaries indexed by split positions.
- temporary dictionaries are then collected into a final list r containing dictionaries with split values for each key.