将项添加到字典中

时间:2015-01-19 01:49:47

标签: python dictionary

您好我的代码正在处理我正在处理的项目。我目前正在尝试操纵字典并在其中添加内容,但我的代码有些奇怪。我的功能的第一步是采用如下所示的文本文件:

A;X;Y;Z
B;Y;Z;X
C;Y;Z;X
D;Z;X;Y
E;Z;X;Y

然后我拿出文本行并将它们放入字典中。例如:

defaultdict(<class 'set'>, {'E': {'Z', 'X', 'Y'}, 'C': {'Y', 'Z', 'X'}, 'A': {'X', 'Y', 'Z'}, 'D': {'Z', 'X', 'Y'}, 'B': {'Y', 'Z', 'X'}})

我编写了for循环来执行此操作,但我遇到的问题是,在向字典中添加项时,代码会因某种原因混合字典中的值。

def read_voter_preferences(file : open):
    votes_dict = defaultdict(set)
    for line in file:
        line = line.strip().split(";")
        for i in range(1,4):
            print(votes_dict)
            votes_dict[line[0]].add(line[i])
    return votes_dict

输出为:defaultdict(<class 'set'>, {'E': {'X', 'Y', 'Z'}, 'C': {'X', 'Y', 'Z'}, 'A': {'X', 'Y', 'Z'}, 'D': {'X', 'Y', 'Z'}, 'B': {'X', 'Y', 'Z'}})

当代码将项添加到字典中时,它会混合字典中对此特定项目很重要的项的顺序。我该如何解决? .add()会自动对列表中的项目进行排序吗?谢谢!

2 个答案:

答案 0 :(得分:1)

setdict一样,保留顺序。如果订单(如您所说)很重要,那么您必须使用list a set来维护它。所以,如果你不担心重复:

votes_dict = dict()
for line in file:
    line = line.strip().split(";")
    votes_dict[line[0]] = line[1:]
return votes_dict

请注意,您现在不需要default_dict

如果你需要 维持秩序删除重复项,那么你的生活会更艰难,但仍然不会太糟糕; e.g:

votes_dict = dict()
for line in file:
    line = line.strip().split(";")
    votes_dict[line[0]] = thelist = []
    seen = set()
    for item in line[1:]:
        if item in seen: continue
        thelist.append(item)
        seen.add(item)
return votes_dict

可以偷工减料,避免创建和维护seen,并使用以下内容:

votes_dict = dict()
for line in file:
    line = line.strip().split(";")
    votes_dict[line[0]] = thelist = []
    for item in line[1:]:
        if item in thelist: continue
        thelist.append(item)
return votes_dict

使用列表而不是集合来检查in一般都很糟糕,但对于非常短的列表来说很好,因为这里有一个很好。 (将本地名称作为您正在构建的列表的别名是一种值得记住的技术 - 没有理由重复索引votes_dict: - )。

答案 1 :(得分:0)

语法

{'Z', 'X', 'Y'}

声明 set 项目,其中只有会员资格很重要,而不是订单。因此Python在显示集合时可以自由地重新排序项目。

要保留订单,请使用列表

['Z', 'X', 'Y']