Python - 字典列表中键的值限制
给定一个字典列表,编写一个Python程序来为字典列表中的每个键分配限制。(每个键都有所有键)。
例子:
Input : test_list = [{“gfg” : 4, “is” : 7, “best” : 10}, {“gfg” : 2, “is” : 5, “best” : 9}, {“gfg” : 1, “is” : 2, “best” : 6}]
Output : {‘gfg’: [1, 4], ‘is’: [2, 7], ‘best’: [6, 10]}
Explanation : gfg has min. value to be 1 and maximum to be 4.
Input : test_list = [{“gfg” : 4, “best” : 10}, {“gfg” : 2, “best” : 9}, {“gfg” : 1, “best” : 6}]
Output : {‘gfg’: [1, 4], ‘best’: [6, 10]}
Explanation : best has min. value to be 6 and maximum to be 10.
方法 #1:使用max() + min() + loop + keys()
在这里,我们使用keys() 执行获取所有键的任务,并且使用min() 和max() 计算限制的最小值和最大值。所有字典的迭代都是使用循环进行的。
Python3
# Python3 code to demonstrate working of
# Value limits to keys in Dictionaries List
# Using max() + min() + loop + keys()
# initializing Matrix
test_list = [{"gfg": 4, "is": 7, "best": 10},
{"gfg": 2, "is": 5, "best": 9},
{"gfg": 1, "is": 2, "best": 6}]
# printing original list
print("The original list is : " + str(test_list))
res = dict()
# extraction of all keys
keys = list(test_list[0].keys())
for key in keys:
# assigning ranges to each key
res[key] = [min(sub[key] for sub in test_list), max(sub[key]
for sub in test_list)]
# printing result
print("Keys Ranges : " + str(res))
Python3
# Python3 code to demonstrate working of
# Value limits to keys in Dictionaries List
# Using list comprehension + min() + max() + keys()
# initializing Matrix
test_list = [{"gfg": 4, "is": 7, "best": 10},
{"gfg": 2, "is": 5, "best": 9},
{"gfg": 1, "is": 2, "best": 6}]
# printing original list
print("The original list is : " + str(test_list))
# extraction of all keys
keys = list(test_list[0].keys())
# Dictionary comprehension used as one liner to perform task
res = {key: [min(sub[key] for sub in test_list), max(sub[key]
for sub in test_list)] for key in keys}
# printing result
print("Keys Ranges : " + str(res))
输出:
The original list is : [{‘gfg’: 4, ‘is’: 7, ‘best’: 10}, {‘gfg’: 2, ‘is’: 5, ‘best’: 9}, {‘gfg’: 1, ‘is’: 2, ‘best’: 6}]
Keys Ranges : {‘gfg’: [1, 4], ‘is’: [2, 7], ‘best’: [6, 10]}
方法 #2:使用字典理解+ min() + max() + keys()
在这种情况下,我们使用一个线性字典理解来执行迭代任务,与上述方法类似,只是一种速记。
蟒蛇3
# Python3 code to demonstrate working of
# Value limits to keys in Dictionaries List
# Using list comprehension + min() + max() + keys()
# initializing Matrix
test_list = [{"gfg": 4, "is": 7, "best": 10},
{"gfg": 2, "is": 5, "best": 9},
{"gfg": 1, "is": 2, "best": 6}]
# printing original list
print("The original list is : " + str(test_list))
# extraction of all keys
keys = list(test_list[0].keys())
# Dictionary comprehension used as one liner to perform task
res = {key: [min(sub[key] for sub in test_list), max(sub[key]
for sub in test_list)] for key in keys}
# printing result
print("Keys Ranges : " + str(res))
输出:
The original list is : [{‘gfg’: 4, ‘is’: 7, ‘best’: 10}, {‘gfg’: 2, ‘is’: 5, ‘best’: 9}, {‘gfg’: 1, ‘is’: 2, ‘best’: 6}]
Keys Ranges : {‘gfg’: [1, 4], ‘is’: [2, 7], ‘best’: [6, 10]}