Python – Value List Key Flattening
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform pairing of each value of keys to extract the flattened dictionary. This kind of problem can have application in data domains. Lets discuss certain way in which this task can be performed.
Method #1 : Using loop
This is brute way in which this task can be performed. In this, we iterate for each of key’s values and assign it to its key and construct new key-value pair.
# Python3 code to demonstrate working of # Value List Key Flattening# Using loop # initializing dictionarytest_dict = {'gfg' : [4, 5, 7], 'best' : [10, 12]} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Value List Key Flattening# Using loopres = []for key, vals in test_dict.items(): for ele in vals: res.append({"key": key, "value": ele}) # printing result print("The flattened dictionary : " + str(res)) |
The original dictionary : {'best': [10, 12], 'gfg': [4, 5, 7]}
The flattened dictionary : [{'value': 10, 'key': 'best'}, {'value': 12, 'key': 'best'}, {'value': 4, 'key': 'gfg'}, {'value': 5, 'key': 'gfg'}, {'value': 7, 'key': 'gfg'}]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


