使用字典的自定义键值对创建列表的Python程序
给定一个字典列表,这里的任务是编写一个Python程序,可以将它转换为一个字典,其中包含来自自定义键值的项目。
Input : test_list = [{‘gfg’ : 1, ‘is’ : 4, ‘best’ : 6},
{‘gfg’ : 10, ‘is’ : 3, ‘best’ : 7},
{‘gfg’ : 9, ‘is’ : 4, ‘best’ : 2},
{‘gfg’ : 4, ‘is’ : 1, ‘best’ : 0},
{‘gfg’ : 6, ‘is’ : 3, ‘best’ : 8}], key, value = ‘gfg’, ‘best’
Output : {1: 6, 10: 7, 9: 2, 4: 0, 6: 8}
Explanation : Dictionary with ‘gfg”s keys and ‘best”s values is constructed.
Input : test_list = [{‘gfg’ : 1, ‘is’ : 4, ‘best’ : 6},
{‘gfg’ : 10, ‘is’ : 3, ‘best’ : 7},
{‘gfg’ : 9, ‘is’ : 4, ‘best’ : 2}], key, value = ‘gfg’, ‘best’
Output : {1: 6, 10: 7, 9: 2}
Explanation : Dictionary with ‘gfg”s keys and ‘best”s values is constructed.
方法一:使用循环
在此,字典列表被迭代并提取所需自定义键的值以声明结果字典的键值对。
例子:
Python3
# initializing list
test_list = [{'gfg': 1, 'is': 4, 'best': 6},
{'gfg': 10, 'is': 3, 'best': 7},
{'gfg': 9, 'is': 4, 'best': 2},
{'gfg': 4, 'is': 1, 'best': 0},
{'gfg': 6, 'is': 3, 'best': 8}]
# printing original list
print("The original list is : " + str(test_list))
# initializing key-values
key, value = 'gfg', 'best'
res = dict()
for sub in test_list:
# constructed values
res[sub[key]] = sub[value]
# printing result
print("Dictionary values : " + str(res))
Python3
# initializing list
test_list = [{'gfg': 1, 'is': 4, 'best': 6},
{'gfg': 10, 'is': 3, 'best': 7},
{'gfg': 9, 'is': 4, 'best': 2},
{'gfg': 4, 'is': 1, 'best': 0},
{'gfg': 6, 'is': 3, 'best': 8}]
# printing original list
print("The original list is : " + str(test_list))
# initializing key-values
key, value = 'gfg', 'best'
# dictionary comprehension for one liner
res = {sub[key]: sub[value] for sub in test_list}
# printing result
print("Dictionary values : " + str(res))
输出:
The original list is : [{‘gfg’: 1, ‘is’: 4, ‘best’: 6}, {‘gfg’: 10, ‘is’: 3, ‘best’: 7}, {‘gfg’: 9, ‘is’: 4, ‘best’: 2}, {‘gfg’: 4, ‘is’: 1, ‘best’: 0}, {‘gfg’: 6, ‘is’: 3, ‘best’: 8}]
Dictionary values : {1: 6, 10: 7, 9: 2, 4: 0, 6: 8}
方法二:使用字典理解
在这种情况下,我们执行与上述方法类似的任务,不同之处在于字典理解用于提供一种替代解决方案的线性替代方案。
例子:
蟒蛇3
# initializing list
test_list = [{'gfg': 1, 'is': 4, 'best': 6},
{'gfg': 10, 'is': 3, 'best': 7},
{'gfg': 9, 'is': 4, 'best': 2},
{'gfg': 4, 'is': 1, 'best': 0},
{'gfg': 6, 'is': 3, 'best': 8}]
# printing original list
print("The original list is : " + str(test_list))
# initializing key-values
key, value = 'gfg', 'best'
# dictionary comprehension for one liner
res = {sub[key]: sub[value] for sub in test_list}
# printing result
print("Dictionary values : " + str(res))
输出:
The original list is : [{‘gfg’: 1, ‘is’: 4, ‘best’: 6}, {‘gfg’: 10, ‘is’: 3, ‘best’: 7}, {‘gfg’: 9, ‘is’: 4, ‘best’: 2}, {‘gfg’: 4, ‘is’: 1, ‘best’: 0}, {‘gfg’: 6, ‘is’: 3, ‘best’: 8}]
Dictionary values : {1: 6, 10: 7, 9: 2, 4: 0, 6: 8}