簡體   English   中英

Python:排序字典詞典

[英]Python: sorting dictionary of dictionaries

我有一個dict(也是一個更大的dict的關鍵)看起來像

wd[wc][dist][True]={'course': {'#': 1, 'Fisher': 4.0},
 'i': {'#': 1, 'Fisher': -0.2222222222222222},
 'of': {'#': 1, 'Fisher': 2.0},
 'will': {'#': 1, 'Fisher': 3.5}}

我想通過相應的'Fisher'值對關鍵詞(在最高級別)進行排序......以便輸出看起來像

wd[wc][dist][True]={'course': {'Fisher': 4.0, '#': 1}, 'will': {'Fisher': 3.5, '#': 1}, 'of': {'Fisher': 2.0, '#': 1}, 'i': {'Fisher': -0.2222222222222222, '#': 1}}

我已嘗試使用items()和sorted()但無法解決...請幫助我:(

您不能對dict進行排序,但可以獲得鍵,值或(鍵,值)對的排序列表。

>>> dic = {'i': {'Fisher': -0.2222222222222222, '#': 1}, 'of': {'Fisher': 2.0, '#': 1}, 'will': {'Fisher': 3.5, '#': 1}, 'course': {'Fisher': 4.0, '#': 1}}

>>> sorted(dic.items(), key=lambda x: x[1]['Fisher'], reverse=True)
[('course', {'Fisher': 4.0, '#': 1}),
 ('will', {'Fisher': 3.5, '#': 1}),
 ('of', {'Fisher': 2.0, '#': 1}),
 ('i', {'Fisher': -0.2222222222222222, '#': 1})
]

或者在獲取排序(鍵,值)對后創建collections.OrderedDict (在Python 2.7中引入):

>>> from collections import OrderedDict
>>> od = OrderedDict(sorted(dic.items(), key=lambda x: x[1]['Fisher'], reverse=True))
>>> od
OrderedDict([
('course', {'Fisher': 4.0, '#': 1}),
('will', {'Fisher': 3.5, '#': 1}),
('of', {'Fisher': 2.0, '#': 1}),
('i', {'Fisher': -0.2222222222222222, '#': 1})
])

對於你的字典,試試這個:

>>> from collections import OrderedDict
>>> dic = wd[wc][dist][True]
>>> wd[wc][dist][True]= OrderedDict(sorted(dic.items(), key=lambda x: x[1]['Fisher'], reverse=True))

如果您只需要按順序鍵,就可以獲得這樣的列表

dic = {'i': {'Fisher': -0.2222222222222222, '#': 1}, 'of': {'Fisher': 2.0, '#': 1}, 'will': {'Fisher': 3.5, '#': 1}, 'course': {'Fisher': 4.0, '#': 1}}
sorted(dic, key=lambda k: dic[k]['Fisher'])

如果'Fisher'可能丟失,您可以使用它來最后移動這些條目

sorted(dic, key=lambda x:dic[x].get('Fisher', float('inf')))

'-inf'將它們放在開頭

暫無
暫無

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

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