Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Split Dict[String, List[String]] to List[Dict[String, String]] and keep every keys [duplicate]

I'm sorry if it's a duplicate of another question. I've looked for it but couldn't find anything close to this one.

I need to convert a dictionary :

{'id': ['001', '002', '003'], 'tag1': ['val1']}

to a list of dictionaries:

[{'id': '001', 'tag1': 'val1'}, {'id': '002', 'tag1': 'val1'}, {'id': '003', 'tag1': 'val1'}]

Note that this dictionary is taken as an example and I can't assume the number nor the name of keys inside the dictionary.

I already solved my problem using this code:

pfilter = dict()
pfilter["id"] = ["001", "002", "003"]
pfilter["tag1"] = ["val1"]
print(pfilter)

all_values = list(itertools.product(*pfilter.values()))
all_keys = [pfilter.keys()]*len(all_values)
all_dict = [zip(keys, values) for keys, values in zip(all_keys, all_values)]
all_dict = [{k:v for k, v in item} for item in all_dict]
print(all_dict)

I can have more than 2 keys and I don't know their names in advance.

I am looking for a more elegant way of solving this problem.

like image 422
Thomas Jalabert Avatar asked Mar 02 '26 07:03

Thomas Jalabert


1 Answers

Building on the answer of my brother you could to a generic solution this way:

from itertools import product

d = {'id': ['001', '002', '003'], 'tag1': ['val1'], 'other_key': ['o1','o2']}
all_dict = [dict([(k,v) for k,v in zip(d.keys(), item)]) for item in product(*d.values()) ]

like image 109
John Sloper Avatar answered Mar 03 '26 20:03

John Sloper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!