📜  Python - 字典列表中键的值限制

📅  最后修改于: 2022-05-13 01:55:13.981000             🧑  作者: Mango

Python - 字典列表中键的值限制

给定一个字典列表,编写一个Python程序来为字典列表中的每个键分配限制。(每个键都有所有键)。

例子:

方法 #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))


输出:

方法 #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))

输出: