DefaultDict,在附加元素上,保持键按加法顺序排序 [英] DefaultDict ,on append elements, maintain keys sorted in the order of addition

查看:238
本文介绍了DefaultDict,在附加元素上,保持键按加法顺序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个空的defaultdict(list),并将其添加到其中.我希望按添加顺序对键进行排序.我的代码需要输入.

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.

输入:

4
bcdef
abcdefg
bcde
bcdef

我的代码:

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

输出:

bcde             
bcdef
abcdefg

所需的输出

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

在这里,我们使用 setdefault 方法,如果尚未在字典中找到该键,则将设置该键的默认值(第二个参数).并且setdefault返回与该键相对应的值,因此,在这种情况下,如果该键不存在,则会针对该键分配一个新列表,并将其返回.如果密钥已经存在,则将返回与之对应的现有列表.然后,我们只需在返回的列表上调用append.

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.

这篇关于DefaultDict,在附加元素上,保持键按加法顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆