开发者

update method for dictionaries-Python

I have written a code which tries to sort a dictionary using the values rather than keys

""" This module sorts a dictionary based on the values of the keys"""

adict={1:1,2:2,5:1,10:2,44:3,67:2} #adict is an input dictionary 
items=adict.items()## converts the dictionary into a list of tuples

##print items

list_value_key=[ [d[1],d[0]] for d in items] """Interchanges the开发者_Go百科 position of the 
                                                key and the values"""
list_value_key.sort()
print list_value_key

key_list=[ list_value_key[i][1] for i in range(0,len(list_value_key))]

print key_list  ## list of keys sorted on the basis of values 

sorted_adict={}

*for key in key_list:
    sorted_adict.update({key:adict[key]})
    print key,adict[key]

print sorted_adict*

So when I print key_list i get the expected answer, but for the last part of the code where i try to update the dictionary, the order is not what it should be. Below are the results obtained. I am not sure why the "update" method is not working. Any help or pointers is appreciated

result:

sorted_adict={1: 1, 2: 2, 67: 2, 5: 1, 10: 2, 44: 3} 


Python dictionaries, no matter how you insert into them, are unordered. This is the nature of hash tables, in general.

Instead, perhaps you should keep a list of keys in the order their values or sorted, something like: [ 5, 1, 44, ...]

This way, you can access your dictionary in sorted order at a later time.


Don't sort like that.

import operator
adict={1:1,2:2,5:1,10:2,44:3,67:2}
sorted_adict = sorted(adict.iteritems(), key=operator.itemgetter(1))


If you need a dictionary that retains its order, there's a class called OrderedDict in the collections module. You can use the recipes on that page to sort a dictionary and create a new OrderedDict that retains the sort order. The OrderedDict class is available in Python 2.7 or 3.1.


To sort your dictionnary, you could also also use :

adict={1:1,2:2,5:1,10:2,44:3,67:2}
k = adict.keys()
k.sort(cmp=lambda k1,k2: cmp(adict[k1],adict[k2]))

And by the way, it's useless to reuse a dictionnary after that because there are no order in dict (they are just mapping types - you can have keys of different types that are not "comparable").


One problem is that ordinary dictionaries can't be sorted because of the way they're implemented internally. Python 2.7 and 3.1 had a new class namedOrderedDictadded to theircollectionsmodule as @kindall mentioned in his answer. While they can't be sorted exactly either, they do retain or remember the order in which keys and associated values were added to them, regardless of how it was done (including via theupdate() method). This means that you can achieve what you want by adding everything from the input dictionary to anOrderedDictoutput dictionary in the desired order.

To do that, the code you had was on the right track in the sense of creating what you called thelist_value_keylist and sorting it. There's a slightly simpler and faster way to create the initial unsorted version of that list than what you were doing by using the built-inzip()function. Below is code illustrating how to do that:

from collections import OrderedDict

adict = {1:1, 2:2, 5:1, 10:2, 44:3, 67:2} # input dictionary

# zip together and sort pairs by first item (value)
value_keys_list = sorted(zip(adict.values(), adict.keys()))

sorted_adict = OrderedDict() # value sorted output dictionary
for pair in value_keys_list:
    sorted_adict[pair[1]] = pair[0]

print sorted_adict
# OrderedDict([(1, 1), (5, 1), (2, 2), (10, 2), (67, 2), (44, 3)])

The above can be rewritten as a fairly elegant one-liner:

sorted_adict = OrderedDict((pair[1], pair[0])
                   for pair in sorted(zip(adict.values(), adict.keys())))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜