簡體   English   中英

通過在python中對字典進行排序來提取鍵列表

[英]Extract a list of keys by Sorting the dictionary in python

我將程序的輸出作為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. 具有最高值的鍵將首先出現,然后是虛擬列表中的最低值

Dictn = {0:1,1:1,2:2}

預期產出 = [2,0,1]

您可以使用列表comp:

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

在Python3現在可以使用的sorted方法,如所描述這里 ,以按您選擇的任何方式的字典。
查看文檔 ,但在最簡單的情況下,您可以.get字典的值,而對於更復雜的操作,您自己定義一個key函數。

Python3中的字典現在是按順序排序的 ,因此另一種處理方法是在字典創建時進行排序,或者可以使用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]

暫無
暫無

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

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