DefaultDict ,on append elements, maintain keys sorted in the order of addition [duplicate]

老子叫甜甜 提交于 2019-12-07 10:48:56

问题


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

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!