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