Reputation: 171
I have a dictionary,
{"apple" : "20", "orange" : "40", "banana" : "25", "mango" : "50"}
I want to extract the data from this dictionary whose values are in the range 20 - 30.
Example. I want the output should be
apple:20
banana:25
I was thinking to order the dictionary first by the values, but it does not seem to work.
I tried dict= sorted(dict.items(), key=lambda t: t[1])
but the output shows like this:
[("apple", "20"), ("orange" , "40"), ("banana" , "25"), ("mango" , "50")]
How can I get output as:
apple:20
banana:25
Upvotes: 2
Views: 2691
Reputation: 123491
You could use a set
to obtain fast membership testing. Doing so also eliminates the need to convert the dictionary's values to integers since the members of the set
are strings:
d = {"apple": "20", "orange": "40", "banana": "25", "mango": "50"}
limits = set(str(n) for n in range(20, 31))
for key, value in sorted(d.items()):
if value in limits:
print('{}:{}'.format(key, value))
Upvotes: 0
Reputation: 51
Returns a dict {'apple': '20', 'banana': '25'}
>>> d = {"apple" : "20", "orange" : "40", "banana" : "25", "mango" : "50"}
>>> {key: val for key,val in d.items() if 20 <= int(val) <= 30}
{'apple': '20', 'banana': '25'}
Upvotes: 0
Reputation: 73470
You can do the following:
> d = {"apple" : "20", "orange" : "40", "banana" : "25", "mango" : "50"}
> for item in sorted(d.items(), key=lambda i: int(i[1])):
> print ': '.join(item)
apple: 20
banana: 25
orange: 40
mango: 50
sorted
sorts the dict
's items (which are key-value tuples
) by the value using a a specific sorting key
.
Upvotes: 3
Reputation: 71461
Using dictionary comprehension:
the_dict = {"apple" : "20", "orange" : "40", "banana" : "25", "mango" : "50"}
new_dict = {the_dict.keys()[i]:the_dict.values()[i] for i in range(len(the_dict.values())) if int(the_dict.values()[i]) <= 30 and int(the_dict.values()[i] >= 20)}
print new_dict
Upvotes: 0
Reputation: 4528
With using of list comprehension you can extract (key,values)
that their values (first cast to int
) are in range 20-30 :
d = {"apple" : "20", "orange" : "40", "banana" : "25", "mango" : "50"}
[(k,v) for k,v in d.items() if 20 <= int(v) <= 30]
# [('banana', '25'), ('apple', '20')]
Then you can have your desired output.
Upvotes: 1
Reputation: 19174
d = {"apple" : "20", "orange" : "40", "banana" : "25", "mango" : "50"}
for k, v in d.items():
if 20 <= int(v) <= 30:
print(k, ':', v, sep='')
prints
apple:20
banana:25
Upvotes: 1
Reputation: 2676
sample_dict={"apple" : "20", "orange" : "40", "banana" : "25", "mango" : "50"}
for name,num in sample_dict.items():
if int(num) in range(20,31):
print('%s: %s' %(name,num))
Upvotes: 2