Python - 提取字典值列表到列表
有时,在处理字典记录时,我们可能会遇到需要将所有字典值提取到一个单独的列表中的问题。这可能在数据域和 Web 开发中得到应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用map()
+ 生成器表达式
上述功能的组合可以用来解决这个问题。在此,我们使用生成器表达式执行提取值的任务,并使用 map() 来重建值列表。
# Python3 code to demonstrate working of
# Extracting Dictionary values list to List
# Using map() + generator expression
# initializing dictionary
test_dict = {'gfg' : [4, 6, 7, 8],
'is' : [3, 8, 4, 2, 1],
'best' : [9, 5, 2, 1, 0]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Extracting Dictionary values to List
# Using map() + generator expression
res = list(map(list, (ele for ele in test_dict.values())))
# printing result
print("The list of dictionary values : " + str(res))
输出 :
The original dictionary is : {‘is’: [3, 8, 4, 2, 1], ‘gfg’: [4, 6, 7, 8], ‘best’: [9, 5, 2, 1, 0]}
The list of dictionary values : [[3, 8, 4, 2, 1], [4, 6, 7, 8], [9, 5, 2, 1, 0]]
方法 #2:使用map()
上述功能的组合可以用来解决这个问题。在此我们使用 map() 执行提取和重新制作的任务。
# Python3 code to demonstrate working of
# Extracting Dictionary values list to List
# Using map()
# initializing dictionary
test_dict = {'gfg' : [4, 6, 7, 8],
'is' : [3, 8, 4, 2, 1],
'best' : [9, 5, 2, 1, 0]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Extracting Dictionary values to List
# Using map()
res = list(map(list, (test_dict.values())))
# printing result
print("The list of dictionary values : " + str(res))
输出 :
The original dictionary is : {‘is’: [3, 8, 4, 2, 1], ‘gfg’: [4, 6, 7, 8], ‘best’: [9, 5, 2, 1, 0]}
The list of dictionary values : [[3, 8, 4, 2, 1], [4, 6, 7, 8], [9, 5, 2, 1, 0]]