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 dictionary
test_dict = {'gfg' : [4, 5, 7], 'best' : [10, 12]}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Value List Key Flattening
# Using loop
res = []
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)) 


Output :

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'}]
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.