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

让人想犯罪 __ 提交于 2019-12-05 16:25:25

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.

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