天天看點

如何按鍵對字典排序?

{2:3, 1:89, 4:5, 3:0}

{1:89, 2:3, 3:0, 4:5}

什麼?

我檢查了一些文章,但它們都使用了傳回元組的“排序”運算符。

#1樓

字典本身沒有這樣的有序項目,如果您想按某種順序列印它們,下面是一些示例:

在Python 2.4及更高版本中:

mydict = {'carl':40,
          'alan':2,
          'bob':1,
          'danny':3}

for key in sorted(mydict):
    print "%s: %s" % (key, mydict[key])
           

給出:

alan: 2
bob: 1
carl: 40
danny: 3
           

(低于2.4的Python :)

keylist = mydict.keys()
keylist.sort()
for key in keylist:
    print "%s: %s" % (key, mydict[key])
           

資料來源: http : //www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/

#2樓

從Python的

collections

庫文檔中 :

>>> from collections import OrderedDict

>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key -- OrderedDict(sorted(d.items()) also works
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
           

#3樓

在Python 3中。

>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
    print (key, D1[key])
           

1 89
2 3
3 0
4 5
           

#4樓

在這裡,我找到了一些最簡單的解決方案,可以使用

pprint

按鍵對python字典進行排序。 例如。

>>> x = {'a': 10, 'cd': 20, 'b': 30, 'az': 99} 
>>> print x
{'a': 10, 'b': 30, 'az': 99, 'cd': 20}
           

但是在使用pprint時,它将傳回排序的字典

>>> import pprint 
>>> pprint.pprint(x)
{'a': 10, 'az': 99, 'b': 30, 'cd': 20}
           

#5樓

找到了另一種方法:

import json
print json.dumps(d, sort_keys = True)
           

更新:

1.這也對嵌套對象進行排序(感謝@DanielF)。

2. python字典是無序的,是以可用于列印或僅配置設定給str。

#6樓

Python字典是無序的。 通常,這不是問題,因為最常見的用例是進行查找。

執行所需操作的最簡單方法是建立一個

collections.OrderedDict

,按排序順序插入元素。

ordered_dict = collections.OrderedDict([(k, d[k]) for k in sorted(d.keys())])
           

如上面其他建議那樣,如果需要疊代,最簡單的方法是疊代排序的鍵。 例子-

列印按鍵排序的值:

# create the dict
d = {k1:v1, k2:v2,...}
# iterate by keys in sorted order
for k in sorted(d.keys()):
    value = d[k]
    # do something with k, value like print
    print k, value
           

擷取按鍵排序的值清單:

values = [d[k] for k in sorted(d.keys())]
           

#7樓

有許多Python子產品提供字典實作,這些實作将按順序自動維護鍵。 考慮sortedcontainers子產品,它是純Python和快速C實作。 還與其他基準測試的流行選項進行了性能比較 。

如果您需要在疊代過程中不斷添加和删除鍵/值對,則使用有序dict是不适當的解決方案。

>>> from sortedcontainers import SortedDict
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> s = SortedDict(d)
>>> s.items()
[(1, 89), (2, 3), (3, 0), (4, 5)]
           

SortedDict類型還支援索引位置查找和删除,這是内置dict類型無法實作的。

>>> s.iloc[-1]
4
>>> del s.iloc[2]
>>> s.keys()
SortedSet([1, 2, 4])
           

#8樓

隻是:

d = {2:3, 1:89, 4:5, 3:0}
sd = sorted(d.items())

for k,v in sd:
    print k, v
           

輸出:

1 89
2 3
3 0
4 5
           

#9樓

夥計們,你讓事情變得複雜了……這很簡單

from pprint import pprint
Dict={'B':1,'A':2,'C':3}
pprint(Dict)
           

輸出為:

{'A':2,'B':1,'C':3}
           

#10樓

2.7中這兩種方法的時序比較顯示它們實際上是相同的:

>>> setup_string = "a = sorted(dict({2:3, 1:89, 4:5, 3:0}).items())"
>>> timeit.timeit(stmt="[(k, val) for k, val in a]", setup=setup_string, number=10000)
0.003599141953657181

>>> setup_string = "from collections import OrderedDict\n"
>>> setup_string += "a = OrderedDict({1:89, 2:3, 3:0, 4:5})\n"
>>> setup_string += "b = a.items()"
>>> timeit.timeit(stmt="[(k, val) for k, val in b]", setup=setup_string, number=10000)
0.003581275490432745 
           

#11樓

l = dict.keys()
l2 = l
l2.append(0)
l3 = []
for repeater in range(0, len(l)):
    smallnum = float("inf")
    for listitem in l2:
        if listitem < smallnum:
            smallnum = listitem
    l2.remove(smallnum)
    l3.append(smallnum)
l3.remove(0)
l = l3

for listitem in l:
    print(listitem)
           

#12樓

from operator import itemgetter
# if you would like to play with multiple dictionaries then here you go:
# Three dictionaries that are composed of first name and last name.
user = [
    {'fname': 'Mo', 'lname': 'Mahjoub'},
    {'fname': 'Abdo', 'lname': 'Al-hebashi'},
    {'fname': 'Ali', 'lname': 'Muhammad'}
]
#  This loop will sort by the first and the last names.
# notice that in a dictionary order doesn't matter. So it could put the first name first or the last name first. 
for k in sorted (user, key=itemgetter ('fname', 'lname')):
    print (k)

# This one will sort by the first name only.
for x in sorted (user, key=itemgetter ('fname')):
    print (x)
           

#13樓

有一種簡單的方法可以對字典進行排序。

根據您的問題,

解決方案是:

c={2:3, 1:89, 4:5, 3:0}
y=sorted(c.items())
print y
           

(其中c是您的字典的名稱。)

該程式提供以下輸出:

[(1, 89), (2, 3), (3, 0), (4, 5)]
           

就像你想要的。

另一個示例是:

d={"John":36,"Lucy":24,"Albert":32,"Peter":18,"Bill":41}
x=sorted(d.keys())
print x
           

給出輸出:

['Albert', 'Bill', 'John', 'Lucy', 'Peter']

y=sorted(d.values())
print y
           

給出輸出:

[18, 24, 32, 36, 41]

z=sorted(d.items())
print z
           

給出輸出:

[('Albert', 32), ('Bill', 41), ('John', 36), ('Lucy', 24), ('Peter', 18)]
           

是以,通過将其更改為鍵,值和項,您可以按需要列印,希望這會有所幫助!

#14樓

最簡單的解決方案是,您應該獲得一個dict鍵的清單,該鍵是排序順序,然後周遊dict。 例如

a1 = {'a':1, 'b':13, 'd':4, 'c':2, 'e':30}
a1_sorted_keys = sorted(a1, key=a1.get, reverse=True)
for r in a1_sorted_keys:
    print r, a1[r]
           

以下是輸出(降序)

e 30
b 13
d 4
c 2
a 1
           

#15樓

将會生成您想要的東西:

D1 = {2:3, 1:89, 4:5, 3:0}

 sort_dic = {}

 for i in sorted(D1):
     sort_dic.update({i:D1[i]})
 print sort_dic


{1: 89, 2: 3, 3: 0, 4: 5}
           

但這不是執行此操作的正确方法,因為它可能會顯示不同詞典的不同行為,這是我最近學到的。 是以,Tim在我在這裡分享的Query的響應中提出了一種完美的方法。

from collections import OrderedDict
sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[0]))
           

#16樓

我認為最簡單的方法是按鍵對字典進行排序,然後将排序後的key:value對儲存到新字典中。

dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2} 
dict2 = {}                  # create an empty dict to store the sorted values
for key in sorted(dict1.keys()):
    if not key in dict2:    # Depending on the goal, this line may not be neccessary
        dict2[key] = dict1[key]
           

為了更清楚一點:

dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2} 
dict2 = {}                  # create an empty dict to store the sorted     values
for key in sorted(dict1.keys()):
    if not key in dict2:    # Depending on the goal, this line may not be  neccessary
        value = dict1[key]
        dict2[key] = value
           

#17樓

dictionary = {1:[2],2:[],5:[4,5],4:[5],3:[1]}

temp=sorted(dictionary)
sorted_dict = dict([(k,dictionary[k]) for i,k in enumerate(temp)])

sorted_dict:
         {1: [2], 2: [], 3: [1], 4: [5], 5: [4, 5]}
           

#18樓

對于CPython / PyPy 3.6和任何Python 3.7或更高版本,可以使用以下方法輕松完成此操作:

>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{1: 89, 2: 3, 3: 0, 4: 5}
           

#19樓

Python字典在Python 3.6之前是無序的。 在Python 3.6的CPython實作中,字典保留插入順序。 從Python 3.7開始,這将成為一種語言功能。

在Python 3.6的更新日志中( https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-compactdict ):

此新實作的順序保留方面被認為是實作細節,是以不應依賴(将來可能會更改,但是希望在更改語言規範之前,先在幾個發行版中使用該新dict實作該語言,為所有目前和将來的Python實作強制要求保留順序的語義;這還有助于保留與仍舊有效的随機疊代順序的舊版本語言(例如Python 3.5)的向後相容性。

在Python 3.7的文檔中( https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries ):

在字典上執行list(d)會以插入順序傳回字典中使用的所有鍵的清單(如果要對其進行排序,請改用sorted(d))。

是以,與以前的版本不同,您可以在Python 3.6 / 3.7之後對字典進行排序。 如果要對嵌套的字典(包括其中的子字典)進行排序,則可以執行以下操作:

test_dict = {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': 1}}

def dict_reorder(item):
    return {k: sort_dict(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}

reordered_dict = dict_reorder(test_dict)
           

https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb

#20樓

您可以根據問題按關鍵字對目前詞典進行排序,進而建立新詞典。

這是你的字典

d = {2:3, 1:89, 4:5, 3:0}
           

通過使用lambda函數對d排序來建立新字典d1

d1 = dict(sorted(d.items(), key = lambda x:x[0]))
           

d1應該為{1:89,2:3,3:0,4:5},根據d中的鍵排序。

#21樓

或使用

pandas

示範:

>>> d={'B':1,'A':2,'C':3}
>>> df=pd.DataFrame(d,index=[0]).sort_index(axis=1)
   A  B  C
0  2  1  3
>>> df.to_dict('int')[0]
{'A': 2, 'B': 1, 'C': 3}
>>> 
           

看到:

這個文檔

大熊貓的文獻資料

#22樓

我提出單行字典排序。

>> a = {2:3, 1:89, 4:5, 3:0}
>> c = {i:a[i] for i in sorted(a.keys())}
>> print(c)
{1: 89, 2: 3, 3: 0, 4: 5}
[Finished in 0.4s]
           

希望這會有所幫助。

#23樓

另一種pythonic方法是

def sort_dict(my_dict):
    return sorted(my_dict.items(), key=lambda x :x[1])


           

#24樓

此函數将按其鍵對任何字典進行遞歸排序。 也就是說,如果字典中的任何值也是字典,那麼它也将通過其鍵進行排序。 如果您在CPython 3.6或更高版本上運作,則可以簡單地更改為使用

dict

而不是

OrderedDict

from collections import OrderedDict

def sort_dict(d):
    items = [[k, v] for k, v in sorted(d.items(), key=lambda x: x[0])]
    for item in items:
        if isinstance(item[1], dict):
            item[1] = sort_dict(item[1])
    return OrderedDict(items)
    #return dict(items)
           

#25樓

标準Python字典是無序的。 即使您對(鍵,值)對進行了排序,也無法以保留順序的方式将它們存儲在

dict

中。

最簡單的方法是使用

OrderedDict

,它可以記住元素插入的順序:

In [1]: import collections

In [2]: d = {2:3, 1:89, 4:5, 3:0}

In [3]: od = collections.OrderedDict(sorted(d.items()))

In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
           

沒關系

od

的列印方式; 它會按預期工作:

In [11]: od[1]
Out[11]: 89

In [12]: od[3]
Out[12]: 0

In [13]: for k, v in od.iteritems(): print k, v
   ....: 
1 89
2 3
3 0
4 5
           

Python 3

對于Python 3使用者,需要使用

.items()

而不是

.iteritems()

In [13]: for k, v in od.items(): print(k, v)
   ....: 
1 89
2 3
3 0
4 5
           

#26樓

正如其他人所提到的,字典本質上是無序的。 但是,如果問題僅是按順序顯示字典,則可以覆寫字典子類中的

__str__

方法,并使用此字典類而不是内置

dict

。 例如。

class SortedDisplayDict(dict):
   def __str__(self):
       return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"


>>> d = SortedDisplayDict({2:3, 1:89, 4:5, 3:0})
>>> d
{1: 89, 2: 3, 3: 0, 4: 5}
           

請注意,這不會改變密鑰的存儲方式,疊代時它們傳回的順序等,也不會改變它們在

print

或python控制台上的顯示方式。