3

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.

Thomas Jalabert
  • 1,344
  • 9
  • 19

2 Answers2

2

EDIT: This only answers OPs original wording of the question.

Product is your friend:

from itertools import product

d = {'id': ['001', '002', '003'], 'tag1': ['val1']}
[ {'id':id, 'tag1': tag1 } for id,tag1 in product(d['id'],d['tag1']) ]
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28
2

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()) ]

John Sloper
  • 1,813
  • 12
  • 14
  • Thanks, It does the jobs ! But we could replace `[d[key] for key in d.keys()]` by `d.values()` – Thomas Jalabert Mar 18 '19 at 15:55
  • Actually, it does not do the jobs because: with this dictionnary : `d = {'id': ['001', '002', '003'], 'tag1': ['val1']}` your function return: `[[{'id': '001'}, {'tag1': 'val1'}], [{'id': '002'}, {'tag1': 'val1'}], [{'id': '003'}, {'tag1': 'val1'}]]` and it's not the outcome I need. – Thomas Jalabert Mar 18 '19 at 16:03
  • @ThomasJalabert I have updated the code so that it produces the correct output. – John Sloper Mar 18 '19 at 16:57