【问题标题】:python: sort a nested dictionarypython:对嵌套字典进行排序
【发布时间】:2011-11-21 19:07:55
【问题描述】:

我有一个嵌套字典,类型如下

{id_1 : [ {id_2:score},{id_3:score_2} .... and so on],id_2 :[{id_1:Score_!....]}

所以基本上是一个嵌套字典 现在我想根据分数对每个主要 id 的字典进行排序 所以基本上

{id_1: [{element with max_score},{element_with next max_score....}]... id_2:[{element_with max_score},{element_with next maxx score}...]

此外,该函数应该接受一个参数 say (n),它返回前 n 个匹配项,或者如果 n

【问题讨论】:

  • 您可能在第一个代码 sn-p 中有一个虚假的括号 - 请您检查一下吗?
  • 为什么是内部列表字典的值,而不仅仅是元组?
  • @SvenMarnach 是的,是的。感谢您指出这一点.. 基本上它是一个嵌套字典
  • 就地或您想要一个新对象?

标签: python dictionary nested


【解决方案1】:

您可以将key 参数用于list.sort()。假设外部字典名为d,代码可能如下所示:

for scores in d.itervalues():
    scores.sort(key=lambda x: next(x.itervalues()), reverse=True)

lambda 函数只是提取字典的单个值。

我认为您最好使用元组而不是字典作为列表的值:

{id_1: [(id_2, score_2), (id_3, score_3),...], id_2: [(id_1, score_1),...]}

使用这种数据结构,排序代码将是

for scores in d.itervalues():
    scores.sort(key=lambda x: x[1], reverse=True)

或等效,但稍快

for scores in d.itervalues():
    scores.sort(key=operator.itemgetter(1), reverse=True)

【讨论】:

  • 应该是scores.sort(...)
  • 列表是 d 还是嵌套字典??
  • +1,可能还需要reverse=True,因为 OP 首先想要更高的分数。
  • @Jerod 我不明白。这个答案包含三种可能的解决方案,第一个是基于 OP 提供的确切数据结构。这怎么不回答原来的问题?
猜你喜欢
  • 1970-01-01
  • 2016-10-31
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-01
相关资源
最近更新 更多