Combining values from dictionary of list in Python

PythonServer Side ProgrammingProgramming

Let’s say we have a python dictionary which has lists as it values in the key value pairs. We need to create a list which will represent all possible combinations of the keys and values from the given lists.

With sorted and product

The product function from itertools can be used to create a crtesian product of the iterable supplied to it as parameter. We sort the dictionary and use two for loops to create the combination of all possible key value pairs from the lists in the dictionary.

Example

 Live Demo

import itertools as it
Adict = {
   "Day": ["Tue", "Wed"],
   "Time": ["2pm", "9am"],
}
# Sorting Adict
sorted_Adict = sorted(Adict)
# Using product after sorting
res = [dict(zip(sorted_Adict, prod))
   for prod in it.product(*(Adict[sorted_Adict]
      for sorted_Adict in sorted_Adict))]
# Printing output
print(res)

Output

Running the above code gives us the following result −

[{'Day': 'Tue', 'Time': '2pm'}, {'Day': 'Tue', 'Time': '9am'}, {'Day': 'Wed', 'Time': '2pm'}, {'Day': 'Wed', 'Time': '9am'}]

With zip

In this approach we use zip the function along with the itertools product function to create the combination of all possible keys and values form the dictionary of lists.

Example

 Live Demo

import itertools as it
Adict = {
   "Day": ["Tue", "Wed"],
   "Time": ["2pm", "9am"],
}
# Sorting Adict
sorted_Adict = sorted(Adict)
# Using product after sorting
res = [[{key: value} for (key, value) in zip(Adict, values)]
   for values in it.product(*Adict.values())]
# Printing output
print(res)

Output

Running the above code gives us the following result −

[[{'Day': 'Tue'}, {'Time': '2pm'}], [{'Day': 'Tue'}, {'Time': '9am'}], [{'Day': 'Wed'}, {'Time': '2pm'}], [{'Day': 'Wed'}, {'Time': '9am'}]]
raja
Published on 20-May-2020 13:54:47
Advertisements