How to add dictionary keys with defined values to a list

I'm trying to only add keys with a value >= n to my list, however I can't give the key an argument.

n = 2
dict = {'a': 1, 'b': 2, 'c': 3}
for i in dict:
  if dict[i] >= n:
    list(dict.keys([i])

When I try this, it tells me I can't give .keys() an argument. But if I remove the argument, all keys are added, regardless of value

Any help?

Upvotes: 1

Views: 495

Answers (2)

Tanveer Alam
Tanveer Alam

Reputation: 5275

You don't need to call .keys() method of dict as you are already iterating data_dict's keys using for loop.

n = 2
data_dict = {'a': 1, 'b': 2, 'c': 3}
lst = []
for i in data_dict:
  if data_dict[i] >= n:
    lst.append(i)

print lst  

Results:

['c', 'b']

You can also achieve this using list comprehension

result = [k for k, v in data_dict.iteritems() if v >= 2]
print result

You should read this: Iterating over Dictionaries.

Upvotes: 2

Reut Sharabani
Reut Sharabani

Reputation: 31339

Try using filter:

filtered_keys = filter(lambda x: d[x] >= n, d.keys())

Or using list comprehension:

filtered_keys = [x for x in d.keys() if d[x]  >= n]

The error in your code is that dict.keys returns all keys, as the docs mention:

Return a copy of the dictionary’s list of keys.

What you want is one key at a time, which list comprehension gives you. Also, when filtering, which is basically what you do, consider using the appropriate method (filter).

Upvotes: 0

Related Questions