Python – 将嵌套字典转换为映射元组
有时,在使用Python字典时,我们可能会遇到需要将嵌套字典转换为映射元组的问题。此类问题可能发生在 Web 开发和日常编程中。让我们讨论可以执行此任务的某些方式。
Input : test_dict = {‘gfg’ : {‘x’ : 5, ‘y’ : 6, ‘z’: 3}, ‘best’ : {‘x’ : 8, ‘y’ : 3, ‘z’: 5}}
Output : [(‘x’, (5, 8)), (‘y’, (6, 3)), (‘z’, (3, 5))]
Input : test_dict = {‘gfg’ : {‘x’ : 5, ‘y’ : 6, ‘z’: 3}}
Output : [(‘x’, (5, )), (‘y’, (6, )), (‘z’, (3, ))]
方法 #1:使用列表理解 + 生成器表达式
上述功能的组合可以用来解决这个问题。在此,我们使用列表理解执行创建元组的任务,生成器表达式通过使用 values() 提取值来帮助分组。
# Python3 code to demonstrate working of
# Convert Nested dictionary to Mapped Tuple
# Using list comprehension + generator expression
# initializing dictionary
test_dict = {'gfg' : {'x' : 5, 'y' : 6}, 'is' : {'x' : 1, 'y' : 4},
'best' : {'x' : 8, 'y' : 3}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Convert Nested dictionary to Mapped Tuple
# Using list comprehension + generator expression
res = [(key, tuple(sub[key] for sub in test_dict.values()))
for key in test_dict['gfg']]
# printing result
print("The grouped dictionary : " + str(res))
The original dictionary is : {‘gfg’: {‘x’: 5, ‘y’: 6}, ‘is’: {‘x’: 1, ‘y’: 4}, ‘best’: {‘x’: 8, ‘y’: 3}}
The grouped dictionary : [(‘x’, (5, 1, 8)), (‘y’, (6, 4, 3))]
方法 #2:使用defaultdict()
+ 循环
这是可以执行此任务的另一种方式。在此,我们使用 defaultdict() 执行映射任务,嵌套字典的键并使用循环重新创建值列表。此方法对旧版本的Python很有用。
# Python3 code to demonstrate working of
# Convert Nested dictionary to Mapped Tuple
# Using defaultdict() + loop
from collections import defaultdict
# initializing dictionary
test_dict = {'gfg' : {'x' : 5, 'y' : 6}, 'is' : {'x' : 1, 'y' : 4},
'best' : {'x' : 8, 'y' : 3}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Convert Nested dictionary to Mapped Tuple
# Using defaultdict() + loop
res = defaultdict(tuple)
for key, val in test_dict.items():
for ele in val:
res[ele] += (val[ele], )
# printing result
print("The grouped dictionary : " + str(list(res.items()))
The original dictionary is : {‘gfg’: {‘x’: 5, ‘y’: 6}, ‘is’: {‘x’: 1, ‘y’: 4}, ‘best’: {‘x’: 8, ‘y’: 3}}
The grouped dictionary : [(‘x’, (5, 1, 8)), (‘y’, (6, 4, 3))]