【问题标题】:Extract a list of keys by Sorting the dictionary in python通过在python中对字典进行排序来提取键列表
【发布时间】:2019-07-03 17:55:40
【问题描述】:

我的程序输出为 python 字典,我想要来自 dictn 的键列表:

s = "cool_ice_wifi"
r = ["water_is_cool", "cold_ice_drink", "cool_wifi_speed"]
good_list=s.split("_")
dictn={}
for i in range(len(r)):
    split_review=r[i].split("_")
    counter=0
    for  good_word in good_list:
        if good_word in split_review:
          counter=counter+1
          d1={i:counter}
          dictn.update(d1)

print(dictn)

我们应该得到密钥的条件:

  1. 具有相同值的键将复制索引,因为它在虚拟列表中。
  2. 具有最高值的键将首先出现在虚拟列表中,然后是最低值

字典={0: 1, 1: 1, 2: 2}

预期输出 = [2,0,1]

【问题讨论】:

  • 打印(list(dictn.keys()))
  • 它不会给出所需的顺序
  • [2, 1, 0] 我们得到这个订单

标签: python dictionary


【解决方案1】:

您可以使用列表组合:

[key for key in sorted(dictn, key=dictn.get, reverse=True)]

【讨论】:

    【解决方案2】:

    在 Python3 中,现在可以使用 sorted 方法(如 here 所述)以您选择的任何方式对字典进行排序。
    查看documentation,但在最简单的情况下,您可以.get 字典的值,而对于更复杂的操作,您可以自己定义一个key 函数。

    Python3 中的字典现在是 insertion-ordered,因此另一种方法是在创建字典时进行排序,或者您可以使用 OrderedDict。

    这是第一个选项的示例,我认为这是最简单的

    >>> a = {}
    >>> a[0] = 1
    >>> a[1] = 1
    >>> a[2] = 2
    >>> print(a)
    {0: 1, 1: 1, 2: 2}
    >>>
    >>> [(k) for k in sorted(a, key=a.get, reverse=True)]
    [2, 0, 1]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-13
      • 2011-12-22
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      • 1970-01-01
      相关资源
      最近更新 更多