Kallol
Kallol

Reputation: 2189

Find the keys using the values with some conditions in a dictionary using python?

I have a dictionary like this:

 {'1956': 21,
     '2188': 76,
     '1307': 9,
     '1305': 22,
     '2196': 64,
     '3161': 1,
     '1025': 22,
     '321': 60,
     '1959': 1,
     '1342': 7,
     '3264': 2}

Where every keys are unique, I want to fetch those keys from the dictionary whose values are more than 60.

The output look like:

  ['2188','2196']

I can do it using a loop iteration using get('key') with a if condition, But that is a long process, what is the shortcut to do it more efficiently ?

Upvotes: 9

Views: 23670

Answers (3)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

If you want to achieve this without loops, and order does not matter, you can try this:

dc = {'1956': 21, '2188': 76, '1307': 9, '1305': 22, '2196': 64, '3161': 1, '1025': 22, '321': 60, '1959': 1, '1342': 7, '3264': 2}

dc_val = sorted(dc.values(), reverse = True)
target_index = dc_val.index(60)
keys = sorted(dc.keys(), key = lambda x: dc[x])
target_keys = keys[-target_index:]
print(target_keys)

>>> ['2196', '2188']

Here we want to sort the dictionary by values, and pick the index of the value 60, and get all keys corresponding to the values after that index. So first the reversed sorted values are stored in dc_val, why reversed? Because in case there are multiple 60s, then it will be vital for the following method. So let's say you had 2 keys with value 60, then dc_val would have:

[76, 64, 60, 60, 22, 22, 21, 9, 7, 2, 1, 1]

Now target_index would be the first index in the list where 60 occurs, which is 2, i.e. the third index. Then keys holds the keys sorted (not reversed) according to their values. Then our target_keys becomes the elements after the third last element, we can access this by our target_index like this: keys[-target_index:].

Upvotes: 1

Yash
Yash

Reputation: 3576

keyValue =  {'1956': 21,
     '2188': 76,
     '1307': 9,
     '1305': 22,
     '2196': 64,
     '3161': 1,
     '1025': 22,
     '321': 60,
     '1959': 1,
     '1342': 7,
     '3264': 2}

for key, value in keyValue.items():
    if value > 60:
        print(key)

# Or just:
print([key for key, value in keyValue.items() if value > 60])

Upvotes: 1

ipaleka
ipaleka

Reputation: 3957

[k for k, v in mydict.items() if v > 60]

Upvotes: 17

Related Questions