Python – 嵌套字典组合
有时,在使用Python字典时,我们可能会遇到需要构造具有不同值的字典键的所有组合的问题。这个问题可以应用在游戏和日常编程等领域。让我们讨论一下我们可以执行此任务的某种方式。
Input : test_dict = {‘gfg’: {‘is’ : [6], ‘for’ : [10], ‘best’: [4]}}
Output : {‘gfg0’: {‘for’: 10, ‘best’: 4, ‘is’: 6}}
Input : test_dict = {‘gfg’: {‘best’ : [10]}}
Output : {‘gfg0’: {‘best’: 10}}
方法:使用product() + dictionary comprehension + zip()
上述功能的组合可以用来解决这个问题。在此,我们使用 product 提取所有可能的组合, zip() 执行将键与过滤后的值配对的任务,字典理解用于存储所有构建的字典。
# 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))
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}}