简体   繁体   中英

How to transform a dictionary of strings to lists to a list of dictionaries?

How can I transform a dictionary of strings to lists to a list of dictionaries that map strings to values in those lists? For example, the following dictionary

{'a': [1,2],
 'b': ['x', 'y', 'z']}

would be transformed into the following list

[{'a': 1, 'b': 'x'}, {'a': 1, 'b': 'y'}, {'a': 1, 'b': 'z'},
 {'a': 2, 'b': 'x'}, {'a': 2, 'b': 'y'}, {'a': 2, 'b': 'z'},]

The main thing you want here is the product of the values, and then to recreate the dictionaries. We can actually do this easily with the help of itertools.product() :

>>> from itertools import product
>>> test = {'a': [1, 2], 'b': ['x', 'y', 'z']}
>>> [dict(zip(test.keys(), part)) for part in product(*test.values())]
[{'a': 1, 'b': 'x'}, {'a': 1, 'b': 'y'}, {'a': 1, 'b': 'z'}, 
 {'a': 2, 'b': 'x'}, {'a': 2, 'b': 'y'}, {'a': 2, 'b': 'z'}]

What we do is we make the product all of the lists in the dictionary, and then take each produced pair (or in the case of more items in the dictionary, arbitrarily long tuple) and zip it to the keys in the dictionary. We then pass this into the dict() builtin to make a dictionary. This is all inside a list comprehension to quickly make the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM