【问题标题】:Sort dict by key and retrieve value按键排序字典并检索值
【发布时间】:2019-06-25 08:58:51
【问题描述】:

给定scores = { 0.0: "bob", 5.2: "alex", 2.8: "carl"}

获取输出[ "bob", "carl", "alex" ]

我可以print([ scores[key] for key in sorted(scores.keys()) ])

这是最好的(最“pythonic”)的方式吗?我在想我可以将scores.items() 与sorted(key=...) 结合使用来避免字典查找,但不确定key 参数是什么。

【问题讨论】:

  • 字典查找没有任何明显的成本。您的解决方案是完美的 Pythnoic,但您可以通过更改算法或数据结构使其成本更高。
  • 是的,您的解决方案很好(不过,.keys() 是不必要的)。
  • @TigerhawkT3 好声音,谢谢
  • 我认为你有正确的路要走。

标签: python python-3.x sorting dictionary


【解决方案1】:

按键对字典进行排序并检索它们的值:

# This is your initial dictionary
scores = { 0.0: "bob", 5.2: "alex", 2.8: "carl"}

# This sorts your dictionary by it's keys as mentioned by x[0]
sorted_scores = {k:v for k, v in sorted(scores.items(), key=lambda x:x[0])}

# Now we are getting all the values in the sorted order and storing it in result
result = list(sorted_scores.values())

# Now, result will be:
['bob', 'carl', 'alex']

# Also sorted_scores will be:
{0.0: 'bob', 2.8: 'carl', 5.2: 'alex'}

【讨论】:

    【解决方案2】:

    请在代码内容下面试试这个代码,它将按键排序。

    scores = { 0.0: "bob", 5.2: "alex", 2.8: "carl"}
    for key, value in sorted(scores.items(), key=lambda kv: kv[0], reverse=True):
        print("%s: %s" % (key, value))
    

    5.2:亚历克斯
    2.8:卡尔
    0.0:鲍勃

    【讨论】:

      【解决方案3】:

      另一种方法是创建一个生成器对象,产生字典的值, 将它们转换成一个列表,然后打印出来。

      print(list(val for val in scores.values()))

      【讨论】:

        【解决方案4】:

        遍历dict 将始终使用键,因此您不必使用.keys() 方法。

        另外,在括号前后尝试not to use 空格。

        scores = {0.0: "bob", 5.2: "alex", 2.8: "carl"}
        print([scores[key] for key in sorted(scores)])
        

        对于更多功能的方法,您还可以使用:

        scores = {0.0: "bob", 5.2: "alex", 2.8: "carl"}
        print(list(map(scores.get, sorted(scores))))
        

        但是您的解决方案非常好:)

        【讨论】:

          【解决方案5】:

          如果您坚持使用.items(),则关键参数是key=lambda t: t[0],但在这种情况下key=lambda t: t 的作用相同(但会根据值打破关系)。 t 默认用作键,因此您无需指定:

          scores = {0.0: "bob", 5.2: "alex", 2.8: "carl"}
          print(sorted(scores.items()))
          

          输出:

          [(0.0, 'bob'), (2.8, 'carl'), (5.2, 'alex')]
          

          现在获取可以像这样“解压缩”的值列表:

          print(
              list(list(zip(*sorted(scores.items())))[1])
          )
          

          【讨论】:

          • 在这种情况下,您不需要 key 进行排序。
          • 我的意思是说 t[0] ,但即便如此我也不需要钥匙
          • 如果你想对items进行排序,我认为你应该这样做next(zip(*sorted(scores.items())))。
          • OP 只要求原始字典中的值列表,而不是键/值元组列表。
          • 哦,好的,我会补充的
          猜你喜欢
          • 2015-10-10
          • 1970-01-01
          • 2013-04-08
          • 1970-01-01
          • 2017-05-30
          • 1970-01-01
          • 1970-01-01
          • 2016-01-23
          • 2014-01-18
          相关资源
          最近更新 更多