How do you turn a dict of lists into a list of dicts with all combinations?

2024/10/14 17:23:14

Basically what I am looking for is the equivalent of itertools.product but for dicts.

For example, say I want to test a function for all combinations of its keyword arguments, I would like to pass lists of permissible values for each keyword argument and then get back a list of dicts.

kwargs_options = {"debug": ["on", "off"], "locale":["de_DE", "en_US", "fr_FR"]

expected ouput:

[{'debug': 'on', 'locale': 'de_DE'},{'debug': 'on', 'locale': 'en_US'},{'debug': 'on', 'locale': 'fr_FR'},{'debug': 'off', 'locale': 'de_DE'},{'debug': 'off', 'locale': 'en_US'},{'debug': 'off', 'locale': 'fr_FR'}]

In order to have a similar API to itertools.product this should return an iterator, which can then be wrapped with a call to list(...) if desired.

Example call:

list(dictproduct(kwargs_options}))

This is similar to Combinations from dictionary with list values using Python but returns a list of two-element dicts rather than two single-element dicts.

Answer

This is what I have come up with:

from itertools import productdef dictproduct(dct):for t in product(*dct.itervalues()):yield dict(zip(dct.iterkeys(), t))

which gives us

>>> list(dictproduct({"debug":["on", "off"], "locale":["de_DE", "en_US", "fr_FR"]}))
[{'debug': 'on', 'locale': 'de_DE'},{'debug': 'on', 'locale': 'en_US'},{'debug': 'on', 'locale': 'fr_FR'},{'debug': 'off', 'locale': 'de_DE'},{'debug': 'off', 'locale': 'en_US'},{'debug': 'off', 'locale': 'fr_FR'}]

This can also be used to efficiently call a function with all combinations of keyword arguments:

def kwproduct(**kwargs):return dictproduct(kwargs)def f(x, y):return 10*x + yfor kwargs in kwproduct(x=[1,2], y=[3,4,5]):print "f({x},{y})={z}".format(z=f(**kwargs), **kwargs)

output:

f(1,3)=13
f(2,3)=23
f(1,4)=14
f(2,4)=24
f(1,5)=15
f(2,5)=25

The benefit of kwproduct over dictproduct is that you don't need to create a dict but it obviously limits you to use valid argument names as keys.

https://en.xdnf.cn/q/117931.html

Related Q&A

Django differentiate between the first time user and returning user

I am using django registration redux for login and auth purposes. I want to do the following.if the user logs in for the first time i want to redirect to URL-"profile/create" if the user is a…

Automatically cropping an image using Python

I want to automatically crop an image using OpenCV into many images, the number of output images is variable. I started by replacing the white background by a transparent background.The input image: I …

How to find highest product of k elements in an array of n length, where k n

I recently tried the question for the highest product of 3 elements. Now I am trying to do it for the k elements. Lets say from 3 now it is asking for 4 elements. I tried to write a generic function so…

Kivy error - Unable to get a window, abort

I installed kivy on my Raspberry pi3, where i run a python program that already works on another pi3.I now am trying to install the same thing on this second pi, and it doesnt work...maybe I forgot som…

Selenium 3.0.2 error with Firefox 50: executable may have wrong permissions

Im trying to use Selenium 3.0.2 with Firefox 50.0.1 in Windows 7. Ive followed the instructions in this post to setup correctly the driver and the paths but Im getting the following error: Traceback (m…

Convert a jpg to a list of lists

Im trying to figure out how to convert a jpg into a list of lists (using python 3.2.3) such that:[ [red,blue,red,etc..], #line1 [blue,red,yellow, etc...], #line2 [orange,yellow,black,et…

TypeError: No to_python (by-value) converter found for C++ type

Im trying to expose my C++ Classes to Python using Boost.Python. Here is a simplyfied version of what Im trying to do:struct Base {virtual ~Base() {};virtual char const *Hello() {printf("Base.Hell…

USB interface in Python

I have this (http://www.gesytec.de/en/download/easylon/p/16/) USB device connected to my Win7. I am just trying to read the vendor ID and product ID. I have Python 2.7.Here is the code,import usb busse…

Django M2M Through extra fields with multiple models

Im trying to figure out the best way to set up the following django model (genericised for security reasons).ThingA:User(M2M through "UserRelation")ThingB:User(M2M through "UserRelation&…

Openpyxl: Worksheet object has no attribute values

My goal is to read in an excel file and view the codes in a pandas dataframe (i.e. = A3) rather than the resulting values from excel executing the codes, which is the pandas default if read in using pa…