I have a dictionary

dict1={'18':['4000','1234'],'12':['7000','4821','187','1860','123','9000']}

I want to sort the keys and values such that, the output is,

dict1={'12':['123','187','1860','4821','7000','9000'],'18':['1234','4000']}

I tried something! but it didn work

>>> for values in dict1:
...     dict1[values].sort()
...
>>> dict1
{'18': ['1234', '4000'], '12': ['123', '1860', '187', '4821', '7000', '9000']}

Full sorting happens for values of '18'. The values of '12' are partially sorted.
but '18' and '12' are themselves not sorted. I don't know whats happening!

Edited 6 Years Ago by knan: n/a

I'm sorry to tell you that, Dictionaries are not meant to be sorted. There are some tricks though, but I suggest you to use lists or tuples.

Yup right! but i want to output that in a sorted manner into a text file.

12 - 123
12 - 187
12 - 1860
12 - 4821
12 - 7000
12 - 9000
18 - 1234
18 - 4000

If i have it like this i can do the above thing easily:

dict1={'12':['123','187','1860','4821','7000','9000'],'18':['1234','4000']}

Edited 6 Years Ago by knan: n/a

Use list comprehensions and sorted

>>> dict1={'12':['123','187','1860','4821','7000','9000'],'18':['1234','4000']}
>>> L = sorted((int(k), sorted(int(x) for x in v)) for k, v in dict1.items())
>>> print L
[(12, [123, 187, 1860, 4821, 7000, 9000]), (18, [1234, 4000])]
>>> M = [(k, x) for k, v in L for x in v]
>>> M
[(12, 123), (12, 187), (12, 1860), (12, 4821), (12, 7000), (12, 9000), (18, 1234), (18, 4000)]
Comments
This is geat! thanks!!! :)

Yes, you can't sort a dictionary, but you can print it in a sorted format.

2. PRINTING (a sorted dict by key)
d = {'A':3, 'B':4, 'C':2', D':1, }
from operator import itemgetter
dlist = sorted(d.items(), key=itemgetter(0)) # sorted by key
for elt in dlist:
print ("--", elt[0], ":", elt[1])

3. PRINTING (a sorted dict by value)
from operator import itemgetter
dlist = sorted(d.items(), key=itemgetter(1)) # sorted by value
for elt in dlist:
print ("--", elt[0], ":", elt[1])

The method of Gribouillis uses a lot of sorted(). They generate new lists. A sort "in place" might be faster and you only need one sort() call

L = [ (k,x) for k, v in dict1.items() for x in v]
L.sort()

Tuples are sorted by element.

Comments
interesting point

Just one caveat ...

# sorting a list of alphanumeric data numerically

a = ['77', '123', '18']

# sort alphabetic
a.sort()

print(a)  # ['123', '18', '77']

# sort numeric
a.sort(key=int)

print(a)  # ['18', '77', '123']

It's worth mentioning that Python has a number of dictionary implementations that maintain the keys in sorted order for faster iterations. Consider the sortedcontainers module which is pure-Python and fast-as-C implementations. You could use the SortedDict type as a replacement for your own dictionary.

This question has already been answered. Start a new discussion instead.