1

I have my program's output as a python dictionary and i want a list of keys from the 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)

The conditions on which we should get the keys:

  1. The keys with the same values will have the index copied as it is in a dummy list.
  2. The keys with highest values will come first and then the lowest in the dummy list

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

Expected output = [2,0,1]

user7422128
  • 902
  • 4
  • 17
  • 41

2 Answers2

2

You can use a list comp:

[key for key in sorted(dictn, key=dictn.get, reverse=True)]
Tdaw
  • 181
  • 4
1

In Python3 it is now possible to use the sorted method, as described here, to sort the dictionary in any way you choose.
Check out the documentation, but in the simplest case you can .get the dictionary's values, while for more complex operations, you'd define a key function yourself.

Dictionaries in Python3 are now insertion-ordered, so one other way to do things is to sort at the moment of dictionary creation, or you could use an OrderedDict.

Here's an example of the first option in action, which I think is the easiest

>>> 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]
hyperTrashPanda
  • 838
  • 5
  • 18