Python | Combining values from dictionary of list
Given a dictionary of list values, the task is to combine every key-value pair in every combination.
Input :
{“Name” : [“Paras”, “Chunky”],
“Site” : [“Geeksforgeeks”, “Cyware”, “Google”] }
Output:
[{‘Site’: ‘Geeksforgeeks’, ‘Name’: ‘Paras’}, {‘Site’: ‘Cyware’, ‘Name’: ‘Paras’},
{‘Site’: ‘Google’, ‘Name’: ‘Paras’}, {‘Site’: ‘Geeksforgeeks’, ‘Name’: ‘Chunky’},
{‘Site’: ‘Cyware’, ‘Name’: ‘Chunky’}, {‘Site’: ‘Google’, ‘Name’: ‘Chunky’}]
Method #1: Using itertools and sorting
Input = {
"Bool" : [ "True" , "False" ],
"Data" : [ "Int" , "Float" , "Long Long" ],
}
import itertools as it
sorted_Input = sorted ( Input )
Output = [ dict ( zip (sorted_Input, prod))
for prod in it.product( * ( Input [sorted_Input]
for sorted_Input in sorted_Input))]
print (Output)
|
Output:
[{‘Bool’: ‘True’, ‘Data’: ‘Int’}, {‘Bool’: ‘True’, ‘Data’: ‘Float’}, {‘Bool’: ‘True’, ‘Data’: ‘Long Long’}, {‘Bool’: ‘False’, ‘Data’: ‘Int’}, {‘Bool’: ‘False’, ‘Data’: ‘Float’}, {‘Bool’: ‘False’, ‘Data’: ‘Long Long’}]
Method #2: Using Zip
import itertools
Input = {
"Bool" : [ "True" , "False" ],
"Data" : [ "Int" , "Float" , "Long Long" ],
}
Output = [[{key: value} for (key, value) in zip ( Input , values)]
for values in itertools.product( * Input .values())]
print (Output)
|
Output:
[[{‘Data’: ‘Int’}, {‘Bool’: ‘True’}], [{‘Data’: ‘Int’}, {‘Bool’: ‘False’}], [{‘Data’: ‘Float’}, {‘Bool’: ‘True’}], [{‘Data’: ‘Float’}, {‘Bool’: ‘False’}], [{‘Data’: ‘Long Long’}, {‘Bool’: ‘True’}], [{‘Data’: ‘Long Long’}, {‘Bool’: ‘False’}]]
Last Updated :
06 Mar, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...