簡體   English   中英

按字典鍵的整數對字典進行排序

[英]Sort dictionary by integers of dictionary keys

假設我有這樣的字典:

thedict={'1':'the','2':2,'3':'five','10':'orange'}

我想按鍵對這本字典進行排序。 如果我執行以下操作:

for key,value in sorted(thedict.iteritems()):
     print key,value

我會得到

1 the
10 orange
2 2
3 five

因為鍵是字符串而不是整數。 我想對它們進行排序,就好像它們是整數一樣,因此條目“ 10,orange”排在最后。 我認為這樣會起作用:

for key,value in sorted(thedict.iteritems(),key=int(operator.itemgetter(0))):
    print key,value

但這產生了這個錯誤:

TypeError: int() argument must be a string or a number, not 'operator.itemgetter'

我在這里做錯了什么? 謝謝!

我認為您可以使用lambda表達式完成此操作:

sorted(thedict.iteritems(), key=lambda x: int(x[0]))
# with Python3, use thedict.items() for an iterator

問題是您將可調用對象傳遞給內置的int()並試圖將int()調用的返回值用作鍵的可調用對象。 您需要為key參數創建一個callable。

您得到的錯誤基本上告訴您,不能使用operator.itemgetter(可調用)調用int() ,只能使用字符串或數字來調用它。

這是人們無法理解的itemgetter吸引他們誤入歧途的時代之一。 只需使用lambda

>>> thedict={'1':'the','2':2,'3':'five','10':'orange'}
>>> sorted(thedict.iteritems(), key=lambda x: int(x[0]))
[('1', 'the'), ('2', 2), ('3', 'five'), ('10', 'orange')]

問題在於int(operator.itemgetter(0))正在立即求值,以便將其作為sorted的參數傳遞。 因此,您要構建一個itemgetter ,然后嘗試對其調用int (這不起作用,因為它不是字符串或數字)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM