beginner
beginner

Reputation: 483

Sorting python dictionary based on keys which contains alphanumeric value

I am new to python. In Python, I want to sort dictionary items based on keys which is alphanumeric.

Code snippet is as follows:

items={'100 kg': u"apple", '500 kg': u"cabbage", '1020 kg': u"banana", '259 GB': u"carrot"}

I want to sort it based on their quantity in ascending order . Is there any way to do this in Python ?

Adding , I sorted dictionary keys using suggested technique. After this I want to add sorted key and its corresponding value in another new dictionary so that I can get dictionary in a sorted way ,but new dictionary is not storing data as in the order that I insert.

So For that I used orderedDict of Python.

For this I am using code as:

import collections

items={'100 kg': u"apple", '500 kg': u"cabbage", '1020 kg': u"banana", '259 kg': u"carrot"}
sorted_keys = sorted(items, key = lambda x : int(x.split()[0]))
sorted_capacity = collections.OrderedDict()
for j in sorted_keys:
    for i in items:
        if j == i:
            print i  
            sorted_capacity[j]=items[j]
            break

Here I am getting error as : AttributeError: 'module' object has no attribute 'OrderedDict' What may be the reason for this?

Upvotes: 0

Views: 976

Answers (2)

beginner
beginner

Reputation: 483

I used

sorted(items, key = lambda x : int(x.split()[0]))

for sorting keys of my dictionary , later i stored keys and the corresponding value in orderedDict since it hold order in which value is entered.

Upvotes: 0

nu11p01n73R
nu11p01n73R

Reputation: 26667

You cannot sort the dictionaries as python dictionaries are unordered.

All you can get is the sorted list of keys or values as

>>> items={'100 kg': u"apple", '500 kg': u"cabbage", '1020 kg': u"banana", '259 GB': u"carrot"}
>>> sorted(items, key = lambda x : int(x.split()[0]))
['100 kg', '259 GB', '500 kg', '1020 kg']

Upvotes: 1

Related Questions