按键排序字典和按键反向排序的不同方式
先决条件: Python中的字典
字典是一个无序、可变和索引的集合。在Python中,字典是用大括号写的,它们有键和值。我们可以使用键访问字典的值。在本文中,我们将讨论 10 种按键对Python字典进行排序以及按键进行反向排序的不同方法。
使用 sorted() 和 keys():
keys()方法返回一个视图对象,该对象显示字典中所有键的列表。 sorted()用于对字典的键进行排序。
例子:
Input:
my_dict = {'c':3, 'a':1, 'd':4, 'b':2}
Output:
a: 1
b: 2
c: 3
d: 4
Python3
# Initialising a dictionary
my_dict = {'c':3, 'a':1, 'd':4, 'b':2}
# Sorting dictionary
sorted_dict = my_dict.keys()
sorted_dict = sorted(sorted_dict)
# Printing sorted dictionary
print("Sorted dictionary using sorted() and keys() is : ")
for key in sorted_dict:
print(key,':', my_dict[key])
Python3
# Initialising dictionary
my_dict = {2: 'three', 1: 'two', 4: 'five', 3: 'four'}
# Sorting dictionary
sorted_dict = sorted(my_dict.items())
# Printing sorted dictionary
print("Sorted dictionary using sorted() and items() is :")
for k, v in sorted_dict:
print(k, v)
Python3
# Initialising a dictionary
my_dict = {'c': 3, 'a': 1, 'd': 4, 'b': 2}
# Sorting dictionary
sorted_dict = sorted(my_dict.keys())
# Printing sorted dictionary
print("Sorted dictionary is : ", sorted_dict)
Python3
# Initialising a dictionary
my_dict = {'red': '#FF0000', 'green': '#008000',
'black': '#000000', 'white': '#FFFFFF'}
# Sorting dictionary in one line
sorted_dict = dict(sorted(my_dict .items()))
# Printing sorted dictionary
print("Sorted dictionary is : ")
for elem in sorted(sorted_dict.items()):
print(elem[0], " ::", elem[1])
Python3
# Initialising a dictionary
my_dict = {'a': 23, 'g': 67, 'e': 12, 45: 90}
# Sorting dictionary using lambda function
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))
# Printing sorted dictionary
print("Sorted dictionary using lambda is : ", sorted_dict)
Python3
# Importing json
import json
# Initialising a dictionary
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
# Sorting and printind in a single line
print("Sorted dictionary is : ", json.dumps(my_dict, sort_keys=True))
Python3
# Importing pprint
import pprint
# Initialising a dictionary
my_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
# Sorting and printing in a single line
print("Sorted dictionary is :")
pprint.pprint(my_dict)
Python
# Importing OrderedDict
from collections import OrderedDict
# Initialising a dictionary
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
# Sorting dictionary
sorted_dict = OrderedDict(sorted(my_dict.items()))
# Printing sorted dictionary
print(sorted_dict)
Python3
# Importing SortedDict
from sortedcontainers import SortedDict
# Initialising a dictionary
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
# Sorting dictionary
sorted_dict = SortedDict(my_dict)
# Printing sorted dictionary
print(sorted_dict)
Python3
class SortedDisplayDict(dict):
def __str__(self):
return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"
# Initialising dictionary and calling class
my_dict = SortedDisplayDict({"b": 2, "c": 3, "a": 1,"d":4})
# Printing dictionary
print(my_dict)
Python3
# Initialising a dictionary
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
# Reverse sorting a dictionary
sorted_dict = sorted(my_dict, reverse=True)
# Printing dictionary
print("Sorted dictionary is :")
for k in sorted_dict:
print(k,':',my_dict[k])
Sorted dictionary using sorted() and keys() is :
a : 1
b : 2
c : 3
d : 4
使用 sorted() 和 items():
items()方法用于返回包含所有字典键和值的列表。它返回一个视图对象,该对象显示给定字典的(键,值)元组对的列表。 sorted()用于对字典的键进行排序。
例子:
Input:
my_dict = {2:'three', 1:'two', 4:'five', 3:'four'}
Output:
1 'two'
2 'three'
3 'Four'
4 'Five'
蟒蛇3
# Initialising dictionary
my_dict = {2: 'three', 1: 'two', 4: 'five', 3: 'four'}
# Sorting dictionary
sorted_dict = sorted(my_dict.items())
# Printing sorted dictionary
print("Sorted dictionary using sorted() and items() is :")
for k, v in sorted_dict:
print(k, v)
Sorted dictionary using sorted() and items() is :
1 two
2 three
3 four
4 five
在单行中使用 sorted() 和 keys():
在这里,我们在一行中同时使用了 sorted() 和 keys()。
例子:
Input:
my_dict = {'c':3, 'a':1, 'd':4, 'b':2}
Output:
Sorted dictionary is : ['a','b','c','d']
蟒蛇3
# Initialising a dictionary
my_dict = {'c': 3, 'a': 1, 'd': 4, 'b': 2}
# Sorting dictionary
sorted_dict = sorted(my_dict.keys())
# Printing sorted dictionary
print("Sorted dictionary is : ", sorted_dict)
Sorted dictionary is : ['a', 'b', 'c', 'd']
在单行中使用 sorted() 和 items()
在这里,我们在一行中同时使用了sorted()和items() 。
例子:
Input:
my_dict = {'red':'#FF0000', 'green':'#008000', 'black':'#000000', 'white':'#FFFFFF'}
Output:
Sorted dictionary is :
black :: #000000
green :: #008000
red :: #FF0000
white :: #FFFFFF
蟒蛇3
# Initialising a dictionary
my_dict = {'red': '#FF0000', 'green': '#008000',
'black': '#000000', 'white': '#FFFFFF'}
# Sorting dictionary in one line
sorted_dict = dict(sorted(my_dict .items()))
# Printing sorted dictionary
print("Sorted dictionary is : ")
for elem in sorted(sorted_dict.items()):
print(elem[0], " ::", elem[1])
Sorted dictionary is :
black :: #000000
green :: #008000
red :: #FF0000
white :: #FFFFFF
使用lambda函数
lambda函数返回特定项元组的键(第 0 个元素),当这些被传递给 sorted() 方法时,它返回一个排序的序列,然后将其类型转换为字典。
例子:
Input:
my_dict = {'a': 23, 'g': 67, 'e': 12, 45: 90}
Output:
Sorted dictionary using lambda is : {'e': 12, 'a': 23, 'g': 67, 45: 90}
蟒蛇3
# Initialising a dictionary
my_dict = {'a': 23, 'g': 67, 'e': 12, 45: 90}
# Sorting dictionary using lambda function
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))
# Printing sorted dictionary
print("Sorted dictionary using lambda is : ", sorted_dict)
Sorted dictionary using lambda is : {'e': 12, 'a': 23, 'g': 67, 45: 90}
6. 使用 json :
Python不允许对字典进行排序。但是在将字典转换为 JSON 时,您可以显式对其进行排序,以便生成的 JSON 按键排序。这对于多维字典来说是正确的。
例子:
Input:
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
Output:
Sorted dictionary is : {"a": 1, "b": 2, "c": 3,"d":4}
蟒蛇3
# Importing json
import json
# Initialising a dictionary
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
# Sorting and printind in a single line
print("Sorted dictionary is : ", json.dumps(my_dict, sort_keys=True))
Sorted dictionary is : {"a": 1, "b": 2, "c": 3, "d": 4}
使用 pprint
Python pprint 模块实际上已经按键对字典进行了排序。 pprint 模块提供了一种以可用作解释器输入的形式“漂亮地打印”任意Python数据结构的功能。
例子:
Input:
my_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Output:
Sorted dictionary is :
{0: 0, 1: 2, 2: 1, 3: 4, 4: 3}
蟒蛇3
# Importing pprint
import pprint
# Initialising a dictionary
my_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
# Sorting and printing in a single line
print("Sorted dictionary is :")
pprint.pprint(my_dict)
使用集合和 OrderedDict
OrderedDict 是一个标准库类,位于 collections 模块中。 OrderedDict 维护插入时键的顺序。
例子:
Input:
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}1}
Output:
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
Python
# Importing OrderedDict
from collections import OrderedDict
# Initialising a dictionary
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
# Sorting dictionary
sorted_dict = OrderedDict(sorted(my_dict.items()))
# Printing sorted dictionary
print(sorted_dict)
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
使用 sortedcontainers 和 SortedDict :
Sorted dict 是一种排序的可变映射,其中键按排序顺序维护。 Sorted dict 是一个有序的可变映射。排序 dict 继承自 dict 来存储项目并维护一个排序的键列表。为此,我们需要安装 sortedcontainers。
sudo pip install sortedcontainers
例子:
Input:
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
Output:
{"a": 1, "b": 2, "c": 3,"d":4}
蟒蛇3
# Importing SortedDict
from sortedcontainers import SortedDict
# Initialising a dictionary
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
# Sorting dictionary
sorted_dict = SortedDict(my_dict)
# Printing sorted dictionary
print(sorted_dict)
输出:
SortedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})
使用类和函数
例子:
Input:
{"b": 2, "c": 3, "a": 1,"d":4}
Output:
{"a": 1, "b": 2, "c": 3,"d":4}
蟒蛇3
class SortedDisplayDict(dict):
def __str__(self):
return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"
# Initialising dictionary and calling class
my_dict = SortedDisplayDict({"b": 2, "c": 3, "a": 1,"d":4})
# Printing dictionary
print(my_dict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
按键反向排序字典
例子:
Input:
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
Output:
Sorted dictionary is :
['a','b','c','d']
蟒蛇3
# Initialising a dictionary
my_dict = {"b": 2, "c": 3, "a": 1,"d":4}
# Reverse sorting a dictionary
sorted_dict = sorted(my_dict, reverse=True)
# Printing dictionary
print("Sorted dictionary is :")
for k in sorted_dict:
print(k,':',my_dict[k])
Sorted dictionary is :
d : 4
c : 3
b : 2
a : 1