4

I created a empty defaultdict(list), and I am adding to it. I want the keys to be sorted in the order of addition. My code takes an input.

Input:

4
bcdef
abcdefg
bcde
bcdef

My Code:

from collections import defaultdict
d = defaultdict(list)
a = int(input())
for i in range(a):
    temp = raw_input()
    d[temp].append(i)
for k in d:
    print k

Output:

bcde             
bcdef
abcdefg

Desired Output

bcdef
abcdefg
bcde
Charan
  • 1,051
  • 3
  • 12
  • 32

1 Answers1

3

You can use collections.OrderedDict to maintain the order of the insertion of keys.

>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> for i in range(4):
...     d.setdefault(input(), []).append(i)
... 
bcdef
abcdefg
bcde
bcdef
>>> print("\n".join(d))
bcdef
abcdefg
bcde

Here, we use setdefault method, which will set the default value (the second argument) for the key, if it is not found in the dictionary already. And the setdefault returns the value corresponding to the key, so in this case, if the key is not there, then a new list is assigned against the key and it will be returned. If the key already exists, then the existing list corresponding to that will be returned. And we simply call append on the list returned.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Thanks,solved my problem, but I have a doubt. I read `defaultdict(list)` is faster than `dict.setdefault` . I tried `OrderedDict(list)` but it gave an error. So, with `OrderedDict()` , `dict.setdefault` is the only way. right? – Charan Aug 02 '15 at 11:12
  • 1
    @Charan Correct, with `OrderedDict`, you can use only `setdefault`. – thefourtheye Aug 02 '15 at 11:57