Python – 不同的扁平化字典
有时,在使用字典时,我们可以拥有本身就是非常复杂嵌套的一部分的键,我们希望将特定键嵌套的所有键和值提取到单独的列表中。这类问题可以在许多领域都有应用,例如 Web 开发。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + isinstance() + 列表推导
上述功能的组合可以用来解决这个问题。在此,我们使用 isinstance() 和循环检查来执行扁平化字典的任务。最后使用列表推导以字典列表的形式编译结果。
Python3
# Python3 code to demonstrate working of
# Distinct Flatten dictionaries
# Using loop + isinstance() + list comprehension
def flatten(temp_dict, temp_list):
for key, val in temp_dict.items():
if isinstance(val, dict):
temp_list.append(key)
flatten(val, temp_list)
else:
temp_list.extend([key, val])
return temp_list
# initializing dictionary
test_dict = {'gfg' : {'is' : 4, "best" : 10}, 'is' : {'for' : { 'geeks' : 8 }}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Distinct Flatten dictionaries
# Using loop + isinstance() + list comprehension
res = [flatten(val, [key]) for key, val in test_dict.items()]
# printing result
print("The flattened dictionary elements : " + str(res))
Python3
# Python3 code to demonstrate working of
# Distinct Flatten dictionaries
# Using yield + isinstance()
def flatten(temp_dict):
if isinstance(temp_dict, dict):
for key, val in temp_dict.items():
yield key
yield from flatten(val)
else:
yield temp_dict
# initializing dictionary
test_dict = {'gfg' : {'is' : 4, "best" : 10}, 'is' : {'for' : { 'geeks' : 8 }}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Distinct Flatten dictionaries
# Using yield + isinstance()
res = [[key, *flatten(val)] for key, val in test_dict.items()]
# printing result
print("The flattened dictionary elements : " + str(res))
输出 :
The original dictionary is : {'is': {'for': {'geeks': 8}}, 'gfg': {'is': 4, 'best': 10}} The flattened dictionary elements : [['is', 'for', 'geeks', 8], ['gfg', 'is', 4, 'best', 10]]
方法 #2:使用 yield + isinstance()
也可以使用上述功能的组合来执行此任务。在此,我们使用使用 yield 的动态数据渲染来使流程紧凑且可读。
Python3
# Python3 code to demonstrate working of
# Distinct Flatten dictionaries
# Using yield + isinstance()
def flatten(temp_dict):
if isinstance(temp_dict, dict):
for key, val in temp_dict.items():
yield key
yield from flatten(val)
else:
yield temp_dict
# initializing dictionary
test_dict = {'gfg' : {'is' : 4, "best" : 10}, 'is' : {'for' : { 'geeks' : 8 }}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Distinct Flatten dictionaries
# Using yield + isinstance()
res = [[key, *flatten(val)] for key, val in test_dict.items()]
# printing result
print("The flattened dictionary elements : " + str(res))
输出 :
The original dictionary is : {'is': {'for': {'geeks': 8}}, 'gfg': {'is': 4, 'best': 10}} The flattened dictionary elements : [['is', 'for', 'geeks', 8], ['gfg', 'is', 4, 'best', 10]]