将字典值转换为集合,同时保留字典

Qan*_*las 3 python dictionary set

我有一个这样的字典:

(100002:“苹果”、100004:“香蕉”、100005:“胡萝卜”)

我试图让我的字典具有键的整数(就像现在一样),但具有值的集(而不是现在的字符串)。我的目标是能够从具有一列的 .csv 文件中读取键(一个 int,即项目 ID 号),然后是大小、形状和颜色等内容的列。我想将此信息添加到我的字典中,以便仅添加字典中已有键的信息。

我的目标字典可能如下所示:

(100002: set(['APPLE','MEDIUM','ROUND','RED']), 100004: set(['Banana','MEDIUM','LONG','YELLOW']), 100005: set(['CARROT','MEDIUM','LONG','ORANGE'])
Run Code Online (Sandbox Code Playgroud)

从我的仅键+字符串作为项目名称的字典开始,我尝试了这样的代码来从 .csv 文件中读取额外信息:

infile = open('FileWithTheData.csv', 'r')
for line in infile.readlines():
    spl_line = line.split(',')
    if int(spl_line[0]) in MyDict.keys():
        MyDict[int(spl_line[0])].update(spl_line[1:])
Run Code Online (Sandbox Code Playgroud)

不幸的是,这个错误说出来了AttributeError: 'str' object has no attribute 'update'。我尝试将字典的值更改为集合,以便我可以更新它们,结果如下:我(100002: set(['A','P','L','E']), 100004: set(['B','A','N']), 100005: set(['C','A','R','O','T'])) 想将值转换为集合,以便当前值的字符串将成为集合中的第一个字符串,而不是而不是将字符串分解为字母并将这些字母组成一组。

当我创建字典时,我还尝试通过将两个列表压缩在一起来将值设置为一组,但这似乎没有任何区别。像这样的 MyDict = dict(zip(listofkeys, set(listofnames))) 仍然使整个 listofnames 列表成为一个集合,但它没有实现我的目标,即使 MyDict 中的每个值成为一个集合,其中包含 listofnames 中的相应字符串:集合中的第一个字符串。

如何将 MyDict 中的值放入一个集合中,以便我可以向该集合中添加其他字符串,而无需将字典中当前值的字符串转换为一组单独的字母?

编辑:我目前通过使用一个函数来生成项目 ID 列表(它们是键)和另一个函数来查找这些项目 ID 以生成相应项目名称的列表(使用两列 .csv 文件作为数据源),然后我将zip它们放在一起。

回答:根据这里的建议,我想出了这个解决方案。我发现具有 set()).update 的部分可以轻松更改为 list()).append 以生成列表而不是集合(以便保留顺序。)我还发现通过 更新更容易。通过将包含名称的列添加到 FileWithTheData.csv 中,我可以创建 .csv 数据输入文件,这样我就不必费力制作字典、将值转换为集合,然后添加更多数据。我的本部分代码现在如下所示:

MyDict = {}
infile = open('FileWithTheData.csv', 'r')
for line in infile.readlines():
    spl_line = line.split(',')
    if int(spl_line[0]) in itemidlist: #note that this is the list I was formerly zipping together with a corresponding list of names to make my dict
        MyDict.setdefault(int(spl_line[0]), list()).append(spl_line[1:])
print MyDict
Run Code Online (Sandbox Code Playgroud)

Nat*_*usa 5

您的错误是因为您的变量最初MyDict将整数映射到字符串。当您尝试更新它时,您会将值视为字符串(set,当它是字符串时)。

您可以为此使用defaultdict :

combined_dict = defaultdict(set)

# first add all the values from MyDict
for key, value in MyDict.iteritems():
    combined_dict[int(key)].add(value)

# then add the values from the file
infile = open('FileWithTheData.csv', 'r')
for line in infile.readlines():
    spl_line = line.split(',')
    combined_dict[int(sp_line[0])].update(spl_line[1:])
Run Code Online (Sandbox Code Playgroud)