Sort dictionary data

John Hunter jdhunter at nitace.bsd.uchicago.edu
Mon May 20 18:05:34 EDT 2002


>>>>> "Marcus" == Marcus Laranjeira <m.laranjeira at datacraft.com.br> writes:

    Marcus> All, I have a dictionary that I need to be sorted. the
    Marcus> current structure is :

    Marcus> dic { 'aaa', 1, 'bbb', 1, 'ccc', 3, 'ddd', 2, 'eee', 1}

    Marcus> and I need this to be sorted and the final dictionary
    Marcus> should be:

    Marcus> dic { 'aaa', 1, 'bbb', 1, 'eee', 1, 'ddd', 2, 'ccc', 3}

The comments of the previous responders are correct in that 1) you
can't have a sorted dictionary and 2) your dictionary is not
constructed right but I think I know what you want anyway.  

You can convert a dictionary to a list of (key, val) tuples and then
sort that list.  

items = dic.items() # returns the list of key, val tuples
items.sort()        # sort the list in place

The default sort of lists of tuples is on the first element of the
tuple.  In your case, you want to sort on the value, which is the 2nd
element of the tuple.  So you need to write a custom sort function.

def compare_on_val( first, second):
	return cmp(first[1], second[1])

dic = { 'aaa': 1, 'bbb': 1, 'ccc': 3, 'ddd': 2, 'eee': 1} 

print 'Using default sort'
items1 = dic.items()
items1.sort()
for (key, val) in items1:
	print key, val

print 'Using custom sort'
items2 = dic.items()
items2.sort(compare_on_val)
for (key, val) in items2:
	print key, val

The output is:

Using default sort
aaa 1
bbb 1
ccc 3
ddd 2
eee 1
Using custom sort
bbb 1
aaa 1
eee 1
ddd 2
ccc 3


Now this doesn't do exactly what I think you want, because it only
sorts on the value and ignores they key. If you want to sort by value,
and within entries that have the same value, sort by key, you'll need:

def compare_on_val_then_key( first, second):
	c1 = cmp(first[1], second[1])
	if c1!=0: return c1
	return cmp(first[0], second[0])

which gives you

Using custom sort
aaa 1
bbb 1
eee 1
ddd 2
ccc 3

John Hunter



More information about the Python-list mailing list