I have an arbitrary python dictionary x
such that the values of each key is itself a list. Here is an example:
x = {"first_name": ["Habib", "Wen-lao"], "second_name": ["Khan", "Chen"]}
Given x
, I would like write a method that computes a list of dictionaries such that each dictionary has the same keys as x but the values are each combination of individual list element.
Additionally, I would like to see all combinations that omit the keys entirely.
So in this case, the result should be:
[{"first_name": "Habib", "second_name": "Khan"},
{"first_name": "Habib", "second_name": "Chen"},
{"first_name": "Habib"},
{"first_name": "Wen-lao", "second_name": "Khan"},
{"first_name": "Wen-lao", "second_name": "Chen"}
{"first_name": "Wen-lao"},
{"second_name": "Khan"},
{"second_name": "Chen"},
{}]
How can I do it? The dictionary x
may have any arbitrary number of keys with arbitrary names. The ordering of the resulting list is irrelevant to me.
Currently I have this:
>>> from collections import OrderedDict
>>> from itertools import product
>>>
>>> def looper(in_dict):
>>> order_of_keys = in_dict.keys()
>>> list_of_tuples = [(key, in_dict[key]) for key in order_of_keys]
>>> ordered_dict = OrderedDict(list_of_tuples)
>>> return [dict(zip(ordered_dict.keys(), t)) for t in product(*ordered_dict.values())]
>>>
>>> x = {"first_name": ["Habib", "Wen-lao"], "second_name": ["Khan", "Chen"]}
>>> print looper(in_dict=x)
[{'first_name': 'Habib', 'second_name': 'Khan'},
{'first_name': 'Habib', 'second_name': 'Chen'},
{'first_name': 'Wen-lao', 'second_name': 'Khan'},
{'first_name': 'Wen-lao', 'second_name': 'Chen'}]
But it doesn't show me the combinations with the keys omitted. How can I do that?
EDIT: This question is related, but is substantially different. There I wanted to know how to create a simple combination of all lists. Here I want to know how to also include combinations with the keys omitted.