Skip to content

# Python – Nested dictionary Combinations

• Last Updated : 14 May, 2020

Sometimes, while working with Python dictionaries, we can have a problem in which we need to construct all the combination of dictionary keys with different values. This problem can have application in domains such as gaming and day-day programming. Lets discuss certain way in which we can perform this task.

Input : test_dict = {‘gfg’: {‘is’ : [6], ‘for’ : [10], ‘best’: [4]}}
Output : {‘gfg0’: {‘for’: 10, ‘best’: 4, ‘is’: 6}}

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

Input : test_dict = {‘gfg’: {‘best’ : [10]}}
Output : {‘gfg0’: {‘best’: 10}}

Method : Using `product() + dictionary comprehension + zip()`
The combination of above functions can be used to solve this problem. In this, we extract all possible combinations using product, zip() performs the task of pairing keys to values filtered and dictionary comprehension is used to store all the constructed dictionaries.

 `# Python3 code to demonstrate working of ``# Nested dictionary Combinations``# Using product() + dictionary comprehension + zip()``from` `itertools ``import` `product`` ` `# initializing dictionary``test_dict ``=` `{``'gfg'``: {``'is'` `: [``6``, ``7``, ``8``], ``'best'``: [``1``, ``9``, ``4``]}}`` ` `# printing original dictionary``print``(``"The original dictionary : "` `+` `str``(test_dict))`` ` `# Nested dictionary Combinations``# Using product() + dictionary comprehension + zip()``res ``=` `{ key ``+` `str``(j) : ``dict``(``zip``(val.keys(), k))``        ``for` `key, val ``in` `test_dict.items()``        ``for` `j, k ``in` `enumerate``(product(``*``val.values()))}`` ` `# printing result ``print``(``"The possible combinations : "` `+` `str``(res)) `
Output :

The original dictionary : {‘gfg’: {‘is’: [6, 7, 8], ‘best’: [1, 9, 4]}}
The possible combinations : {‘gfg5’: {‘is’: 7, ‘best’: 4}, ‘gfg3’: {‘is’: 7, ‘best’: 1}, ‘gfg8’: {‘is’: 8, ‘best’: 4}, ‘gfg2’: {‘is’: 6, ‘best’: 4}, ‘gfg6’: {‘is’: 8, ‘best’: 1}, ‘gfg0’: {‘is’: 6, ‘best’: 1}, ‘gfg1’: {‘is’: 6, ‘best’: 9}, ‘gfg7’: {‘is’: 8, ‘best’: 9}, ‘gfg4’: {‘is’: 7, ‘best’: 9}}

My Personal Notes arrow_drop_up