-1

I have dictionary of lists that I need to sort by the first value in the list. I'm using a defaultdict.

from collections import defaultdict
Dict = defaultdict(list)
Dict['A'].append([100, 'abcd'])
Dict['A'].append([50, 'bgfd'])
Dict['A'].append([150, 'abcd'])

I need to iterate over the dictionary in an ordered manner so that I get:

for Entry in Dict['A']:
     print Entry

Should give:

[50, 'bgfd']
[100, 'abcd']
[150, 'abcd']
Tetra
  • 15
  • 6
user2165857
  • 2,530
  • 7
  • 27
  • 39
  • You can't sort dictionaries, they're unordered. What you want to do is sort the list values in a `defaultdict(list)`. That's fine as list _are_ ordered. You can get a sorted _copy_ of an entry by using `sorted(Dict['A'])`, or you could actually reorder the contents of one by using `Dict['A'].sort()`. – martineau Jul 03 '14 at 17:22

2 Answers2

1

The value is just a list, so you can sort it with sorted():

for Entry in sorted(Dict['A']):
    print Entry

Sorting is lexicographical on the contents of the list; so first ordering is determined by list_a[0] vs. list_b[0], then if those tie, elements 1 are compared, etc.

All this has nothing to do with the defaultdict, that's just the container for the keys and values, but you already retrieved the value.

Demo:

>>> from collections import defaultdict
>>> Dict = defaultdict(list)
>>> Dict['A'].append([100, 'abcd'])
>>> Dict['A'].append([50, 'bgfd'])
>>> Dict['A'].append([150, 'abcd'])
>>> sorted(Dict['A'])
[[50, 'bgfd'], [100, 'abcd'], [150, 'abcd']]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Just use sorted and sort the list stored in Dict['A']:

>>> from collections import defaultdict
>>> Dict = defaultdict(list)
>>> Dict['A'].append([100, 'abcd'])
>>> Dict['A'].append([50, 'bgfd'])
>>> Dict['A'].append([150, 'abcd'])
>>>
>>> for Entry in sorted(Dict['A']):
...     print Entry
...
[50, 'bgfd']
[100, 'abcd']
[150, 'abcd']
>>>