Python——具有唯一值列表的字典
當需要獲得具有唯一值列表的字典時,將使用“set”運算子和列表方法,以及簡單的迭代。
示例
以下是相同的演示 -
my_dictionary = [{'Python' : 11, 'is' : 22}, {'fun' : 11, 'to' : 33}, {'learn' : 22},{'object':9},{'oriented':11}]
print("The dictionary is : " )
print(my_dictionary)
my_result = list(set(value for element in my_dictionary for value in element.values()))
print("The resultant list is : ")
print(my_result)
print("The resultant list after sorting is : ")
my_result.sort()
print(my_result)輸出
The dictionary is :
[{'Python': 11, 'is': 22}, {'fun': 11, 'to': 33}, {'learn': 22}, {'object': 9}, {'oriented': 11}]
The resultant list is :
[33, 11, 22, 9]
The resultant list after sorting is :
[9, 11, 22, 33]解釋
定義了字典列表,並顯示在控制檯上。
透過迭代訪問字典中的值,並轉換為集合。
這種方式,獲得了唯一元素。
然後將其轉換為列表,並分配給變數。
它顯示為控制檯上的輸出。
再次對其排序並在控制檯上顯示。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP