Thursday, July 4, 2024
HomeLanguagesPythonPython | Combining values from dictionary of list

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” : [“Geeksforneveropen”, “Cyware”, “Google”] }

Output:
[{‘Site’: ‘Geeksforneveropen’, ‘Name’: ‘Paras’}, {‘Site’: ‘Cyware’, ‘Name’: ‘Paras’},
{‘Site’: ‘Google’, ‘Name’: ‘Paras’}, {‘Site’: ‘Geeksforneveropen’, ‘Name’: ‘Chunky’},
{‘Site’: ‘Cyware’, ‘Name’: ‘Chunky’}, {‘Site’: ‘Google’, ‘Name’: ‘Chunky’}]

Method #1: Using itertools and sorting




# Python code to combine every key value
# pair in every combinations
  
# List initialization
Input = {
"Bool" : ["True", "False"],
"Data" : ["Int", "Float", "Long Long"],
}
  
# Importing
import itertools as it
  
# Sorting input
sorted_Input = sorted(Input)
  
# Using product after sorting
Output = [dict(zip(sorted_Input, prod)) 
          for prod in it.product(*(Input[sorted_Input]
          for sorted_Input in sorted_Input))]
  
# Printing output
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




# Python code to combine every key value
# pair in every combinations
  
# Importing
import itertools
  
# Input Initialization
Input = {
"Bool" : ["True", "False"],
"Data" : ["Int", "Float", "Long Long"],
}
  
# using zip and product without sorting
Output = [[{key: value} for (key, value) in zip(Input, values)] 
              for values in itertools.product(*Input.values())]
                  
# Printing output
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’}]]

Nango Kalahttps://www.kala.co.za
Experienced Support Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Microsoft Excel, Customer Service, Microsoft Word, Technical Support, and Microsoft Office. Strong information technology professional with a Microsoft Certificate Solutions Expert (Privet Cloud) focused in Information Technology from Broadband Collage Of Technology.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments