Reputation: 151
I have one question about writing a code on dictionaries i have done the coding but i am confused on one part this is what it says the parameter name is sort_by_value: "(dict of {immutable_type:int}) -> list" and the description is "Return a list of keys in the dictionary sorted in ascending order according to their values. Keys with identical values might be sorted in any order. "
and my code that i wrote is
def sort_by_value(dict):
"""
(dict of {immutable_type:int}) -> list """
L = []
for x in dict.values():
L.append(x)
L.sort()
print L
this code ascends it with the value only like say if I had a dictionary
nd = {}
nd['john'] = 109090
nd['albert'] = 1900
nd['Tim'] = 18000
sort_by_value(nd)
I get the list [1900, 18000, 109090] but I need to get the keys associated with those values like I want ['albert', 'Tim', 'john']
I did try giving it a try and tried to introduce another for loop right before Print L I wanted to write
keyList= []
for x in L:
keyList.append(dict.get())
if
but i dont know if that would work please need of helppp
Upvotes: 0
Views: 119
Reputation: 1262
You can use built-in sorted function to sort tuple of that dictionary.
nd = {}
nd['john'] = 109090
nd['albert'] = 1900
nd['Tim'] = 18000
print sorted(nd.items(), key=lambda x: x[1])
Which will return:
[('albert', 1900), ('Tim', 18000), ('john', 109090)]
if you want to get keys only:
print map(lambda x: x[0], sorted(nd.items(), key=lambda x: x[1]))
will give you:
['albert', 'Tim', 'john']
Refer: http://wiki.python.org/moin/HowTo/Sorting/
Upvotes: 1