DefaultDict, when adding items, maintains keys sorted in the order they were added

I created empty defaultdict(list)

and I add to it. I want the keys to be sorted in the order they were added. My code takes 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 result

bcdef
abcdefg
bcde

      

+3


source to share


1 answer


You can use collections.OrderedDict

to maintain the order of 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 are using a method setdefault

that will set a default value (second argument) for the key if it is not already found in the dictionary. And setdefault

returns the value corresponding to the key, so in this case, if the key does not exist, then the new key is assigned against the key and it will be returned. If the key already exists, then an existing list matching this will be returned. And we just call append

on the returned list.

+1


source







All Articles