Python字典排序的方法有以下幾種:
d = {'b': 2, 'a': 1, 'c': 3}
sorted_keys = sorted(d.keys())
輸出結(jié)果為:[‘a(chǎn)’, ‘b’, ‘c’]
或者對(duì)字典的值進(jìn)行排序:
d = {'b': 2, 'a': 1, 'c': 3}
sorted_values = sorted(d.values())
輸出結(jié)果為:[1, 2, 3]
from operator import itemgetter
d = {'b': 2, 'a': 1, 'c': 3}
sorted_items = sorted(d.items(), key=itemgetter(0))
輸出結(jié)果為:[(‘a(chǎn)’, 1), (‘b’, 2), (‘c’, 3)]
根據(jù)字典的值進(jìn)行排序:
from operator import itemgetter
d = {'b': 2, 'a': 1, 'c': 3}
sorted_items = sorted(d.items(), key=itemgetter(1))
輸出結(jié)果為:[(‘a(chǎn)’, 1), (‘b’, 2), (‘c’, 3)]
d = {'b': 2, 'a': 1, 'c': 3}
sorted_items = sorted(d.items(), key=lambda x: x[0])
輸出結(jié)果為:[(‘a(chǎn)’, 1), (‘b’, 2), (‘c’, 3)]
根據(jù)字典的值進(jìn)行排序:
d = {'b': 2, 'a': 1, 'c': 3}
sorted_items = sorted(d.items(), key=lambda x: x[1])
輸出結(jié)果為:[(‘a(chǎn)’, 1), (‘b’, 2), (‘c’, 3)]
這些方法可以根據(jù)需要選擇合適的方法對(duì)字典進(jìn)行排序。