This question already has an answer here:
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
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.
来源:https://stackoverflow.com/questions/31770251/defaultdict-on-append-elements-maintain-keys-sorted-in-the-order-of-addition