先决条件: Python的字典
字典是一个无序、可变和索引的集合。在Python,字典是用大括号写的,它们有键和值。我们可以使用键访问字典的值。在本文中,讨论了按值对Python字典进行排序以及按值进行反向排序的 10 种不同方法。
将 lambda函数与 items() 和 sorted() 一起使用: lambda函数返回特定项元组的键(第0个元素),当这些被传递给 sorted() 方法时,它返回一个排序的序列,然后键入- 铸成字典。 keys()方法返回一个视图对象,该对象显示字典中所有键的列表。 sorted()用于对字典的键进行排序。
例子:
Input: my_dict = {2: ‘three’, 1: ‘two’}
Output: [(2, ‘three’), (1, ‘two’)]
下面是使用 lambda函数的实现:
Python3
# Python program to sort dictionary
# by value using lambda function
# Initialize a dictionary
my_dict = {2: 'three',
1: 'two'}
# Sort the dictionary
sorted_dict = sorted(
my_dict.items(),
key = lambda kv: kv[1])
# Print sorted dictionary
print("Sorted dictionary is :",
sorted_dict)
Python3
# Python program to sort dictionary
# by value using item function
# Initialize a dictionary
my_dict = {'c': 3,
'a': 1,
'd': 4,
'b': 2}
# Sorting dictionary
sorted_dict = sorted([(value, key)
for (key, value) in my_dict.items()])
# Print sorted dictionary
print("Sorted dictionary is :")
print(sorted_dict)
Python3
# Python program to sort dictionary
# by value using sorted() and get()
# Initialize a dictionary
my_dict = {'red': '# FF0000', 'green': '# 008000',
'black': '# 000000', 'white': '# FFFFFF'}
# Sort and print dictionary
print("Sorted dictionary is :")
for w in sorted(my_dict, key = my_dict.get):
print(w, my_dict[w])
Python3
# Python program to sort dictionary
# by value using itemgetter() function
# Importing OrderedDict
import operator
# Initialize a dictionary
my_dict = {'a': 23,
'g': 67,
'e': 12,
45: 90}
# Sorting dictionary
sorted_dict = sorted(my_dict.items(), \
key = operator.itemgetter(1))
# Printing sorted dictionary
print("Sorted dictionary is :")
print(sorted_dict)
Python3
# Python program to sort dictionary
# by value using OrderedDict
# Import OrderedDict
from collections import OrderedDict
# Initialize a dictionary
my_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
# Sort dictionary
sorted_dict = OrderedDict(sorted(\
my_dict.items(), key = lambda x: x[1]))
# Print the sorted dictionary
print("Sorted dcitonary is :")
print(sorted_dict)
Python3
# Python program to sort dictionary
# by value using OrderedDict
# Import Counter
from collections import Counter
# Initialize a dictionary
my_dict = {'hello': 1, 'python': 5, 'world': 3}
# Sort and print the dictionary
sorted_dict = Counter(my_dict)
print("Sorted dictionary is :")
print(sorted_dict.most_common()[::-1])
Python3
# Python program to sort dictionary
# by value using sorted setting
# reverse parameter to true
# Initialize a dictionary
my_dict = {'red': '# FF0000', 'green': '# 008000',
'black': '# 000000', 'white': '# FFFFFF'}
# Sort and print the dictionary
print("Sorted dictionary is :")
for w in sorted(my_dict, key = my_dict.get, \
reverse = True):
print(w, my_dict[w])
Sorted dictionary is : [(2, 'three'), (1, 'two')]
单独使用 items() :方法 items() 单独使用两个变量,即键和值,以按值对字典进行排序。
例子:
Input: my_dict = {‘c’: 3, ‘a’: 1, ‘d’: 4, ‘b’: 2}
Output: [(1, ‘a’), (2, ‘b’), (3, ‘c’), (4, ‘d’)]
下面是使用方法 items() 的实现:
蟒蛇3
# Python program to sort dictionary
# by value using item function
# Initialize a dictionary
my_dict = {'c': 3,
'a': 1,
'd': 4,
'b': 2}
# Sorting dictionary
sorted_dict = sorted([(value, key)
for (key, value) in my_dict.items()])
# Print sorted dictionary
print("Sorted dictionary is :")
print(sorted_dict)
Sorted dictionary is :
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
使用 sorted() 和 get() :方法 get() 返回给定键的值(如果存在于字典中)。如果没有,那么它将返回None 。
例子:
Input: my_dict = {‘red’:’#FF0000′, ‘green’:’#008000′, ‘black’:’#000000′, ‘white’:’#FFFFFF’}
Output:
black #000000
green #008000
red #FF0000
white #FFFFFF
下面是使用 sorted() 和 get() 方法的实现:
蟒蛇3
# Python program to sort dictionary
# by value using sorted() and get()
# Initialize a dictionary
my_dict = {'red': '# FF0000', 'green': '# 008000',
'black': '# 000000', 'white': '# FFFFFF'}
# Sort and print dictionary
print("Sorted dictionary is :")
for w in sorted(my_dict, key = my_dict.get):
print(w, my_dict[w])
Sorted dictionary is :
black # 000000
green # 008000
red # FF0000
white # FFFFFF
使用运算符的itemgetter :
itemgetter(n) 方法构造了一个可调用对象,它假定一个可迭代对象作为输入,并从中取出第 n 个元素。
例子
Input:
my_dict = {‘a’: 23, ‘g’: 67, ‘e’: 12, 45: 90}
Output:
[(‘e’, 12), (‘a’, 23), (‘g’, 67), (45, 90)]
下面是使用 itemgetter() 对字典进行排序的Python程序:
蟒蛇3
# Python program to sort dictionary
# by value using itemgetter() function
# Importing OrderedDict
import operator
# Initialize a dictionary
my_dict = {'a': 23,
'g': 67,
'e': 12,
45: 90}
# Sorting dictionary
sorted_dict = sorted(my_dict.items(), \
key = operator.itemgetter(1))
# Printing sorted dictionary
print("Sorted dictionary is :")
print(sorted_dict)
Sorted dictionary is :
[('e', 12), ('a', 23), ('g', 67), (45, 90)]
从集合中使用 OrderedDict : OrderedDict 是一个标准库类,位于集合模块中。 OrderedDict 维护插入时键的顺序。
例子:
Input: my_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Output: [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
下面是使用 Ordered Dict 的实现:
蟒蛇3
# Python program to sort dictionary
# by value using OrderedDict
# Import OrderedDict
from collections import OrderedDict
# Initialize a dictionary
my_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
# Sort dictionary
sorted_dict = OrderedDict(sorted(\
my_dict.items(), key = lambda x: x[1]))
# Print the sorted dictionary
print("Sorted dcitonary is :")
print(sorted_dict)
Sorted dcitonary is :
OrderedDict([(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)])
使用集合中的计数器:计数器是一个无序集合,其中元素存储为字典键,它们的计数为字典值。计数器元素计数可以是正整数、零或负整数。
例子:
Input: my_dict = {‘hello’: 1, ‘python’: 5, ‘world’: 3}
Output: [(‘hello’, 1), (‘world’, 3), (‘python’, 5)]
下面是使用集合中的 Counter 的实现:
蟒蛇3
# Python program to sort dictionary
# by value using OrderedDict
# Import Counter
from collections import Counter
# Initialize a dictionary
my_dict = {'hello': 1, 'python': 5, 'world': 3}
# Sort and print the dictionary
sorted_dict = Counter(my_dict)
print("Sorted dictionary is :")
print(sorted_dict.most_common()[::-1])
Sorted dictionary is :
[('hello', 1), ('world', 3), ('python', 5)]
按值反向排序字典:升序和降序排序的语法相同。对于反向排序,想法是使用reverse = true。使用函数sorted() 。
例子:
Input:
my_dict = {‘red’:’#FF0000′,
‘green’:’#008000′,
‘black’:’#000000′,
‘white’:’#FFFFFF’}
Output:
black #000000
green #008000
red #FF0000
white #FFFFFF
以下是按值使用反向排序字典的实现:
蟒蛇3
# Python program to sort dictionary
# by value using sorted setting
# reverse parameter to true
# Initialize a dictionary
my_dict = {'red': '# FF0000', 'green': '# 008000',
'black': '# 000000', 'white': '# FFFFFF'}
# Sort and print the dictionary
print("Sorted dictionary is :")
for w in sorted(my_dict, key = my_dict.get, \
reverse = True):
print(w, my_dict[w])
Sorted dictionary is :
white # FFFFFF
red # FF0000
green # 008000
black # 000000