【问题标题】:Python: sorting dictionary of dictionariesPython:字典的排序字典
【发布时间】:2013-05-01 00:34:39
【问题描述】:

我有一个字典(也是一个更大字典的键),看起来像

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() 但无法解决... 请帮帮我:(

【问题讨论】:

标签: python sorting dictionary


【解决方案1】:

您不能对字典进行排序,但可以获得键、值或 (key,values) 对的排序列表。

>>> 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))

【讨论】:

  • 请注意,OrderedDict 仅适用于 Python 2.7 及更高版本。
  • 使用 items() 会导致 KeyError...为什么会这样?
  • @CosmicRabbitMediaInc 您的一本词典可能没有Fisher 键,对吗?尝试all('Fisher' in d[k] for k in d) 并发布输出
  • @jamylak 我试过 print dic.items() 但它本身会导致密钥错误......它仍然与 Fisher 密钥有关吗?顺便说一句,我的 dic 本身也是更大 dic 的键..
  • @CosmicRabbitMediaInc 然后尝试larger_dict[key].items(),或在问题正文中发布较大的dict
【解决方案2】:

如果你只需要按键顺序,你可以得到一个这样的列表

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' 将它们放在开头

【讨论】:

  • 如果条目没有“Fisher”,您将如何完全删除它们?
猜你喜欢
  • 2011-05-18
  • 2011-08-28
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
  • 2015-11-12
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多