Python——限制字典列表中鍵的值
如果需要在字典列表中限制鍵的值,則可以訪問這些鍵,並且可以使用“最小值”和“最大值”方法來限制這些值。
示例
以下是對此方法的演示
my_list = [{"python": 4, "is": 7, "best": 10},{"python": 2, "is": 5, "best": 9},{"python": 1, "is": 2, "best": 6}]
print("The list is :")
print(my_list)
my_result = dict()
keys = list(my_list[0].keys())
for my_elem in keys:
my_result[my_elem] = [min(sub[my_elem] for sub in my_list), max(sub[my_elem] for sub in my_list)]
print("The result is :")
print(my_result)輸出
The list is :
[{'python': 4, 'is': 7, 'best': 10}, {'python': 2, 'is': 5, 'best': 9}, {'python': 1, 'is': 2, 'best': 6}]
The result is :
{'python': [1, 4], 'is': [2, 7], 'best': [6, 10]}說明
定義字典列表,並在控制檯中顯示。
建立空字典。
將字典列表的鍵轉換為列表並存儲到變數中。
對這些值進行迭代,並獲取最小值和最大值。
方法是迭代列表中的元素。
這將在控制檯中顯示為輸出。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP