将dict值转换为一组,同时保留dict [英] Converting dict values into a set while preserving the dict

查看:198
本文介绍了将dict值转换为一组,同时保留dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



(100002:'APPLE',100004:'BANANA',100005:'CARROT')



我试图让我的dict对于键(如现在这样)有int,但是为这些值设置(而不是现在的字符串)。我的目标是能够从.csv文件中读取一个键(一个int是项目ID号)的列,然后是像尺寸,形状和颜色的列。我想将这些信息添加到我的dict中,以便只添加已经在dict中的密钥的信息。



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

 (100002:set(['APPLE','MEDIUM','ROUND','RED']),100004:set(['Banana ','MEDIUM','LONG','YELLOW']),100005:set(['CARROT','MEDIUM','LONG','ORANGE'])
/ pre>

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

  infile = open('FileWithTheData.csv','r')
用于infile.readlines()中的行:
spl_line = line.split(',')
如果MyDict.keys()中的int(spl_line [0]):
MyDict [int(spl_line [0])] update(spl_line [ 1:])

不幸的是,这个错误说出 AttributeError:'str'没有属性'update'。我尝试更改我的字典的v ($'c $ c>(100002:set(['A','P','L','E']),100004:设置(['B','A','N']),100005:set(['C','A','R','O','T']))
我想将值转换为一个集合,使当前该值的字符串将是集合中的第一个字符串,而不是将字符串分解成字母,并创建一组这些字母。



当我通过将两个列表压缩在一起创建dict时,我也尝试将值设置为一组,但似乎没有任何区别。这样的
MyDict = dict(zip(listofkeys,set(listofnames)))
仍然使整个listofnames列表成一个集合,但它并没有达到我的目标,使MyDict中的每个值成为设置与listofnames对应的字符串作为集合中的第一个字符串。



如何将MyDict中的值设置为一个集合,以便我可以添加额外的字符串设置没有将当前的字符串转换成一组单独的字母?



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



ANSWER:
使用这里的建议,我想出了这个解决方案。我发现有set())更新的部分可以很容易地被更改为list())。append来产生一个列表,而不是一个集合(以便保持顺序)。我还发现更容易更新。 csv数据输入文件通过将包含名称的列添加到FileWithTheData.csv中,以便我不必混淆使用dict,将值转换为集合,然后添加更多数据。我的代码现在看起来像这样:

  MyDict = {} 
infile = open('FileWithTheData.csv ','r')
for infile.readlines():
spl_line = line.split(',')
if item(spl_line [0])in itemidlist:#note这是我以前列出的一个列表,使用我的dict命令
MyDict.setdefault(int(spl_line [0]),list())。append(spl_line [1:])
打印MyDict


解决方案

你的错误是因为 MyDict 将整数映射到字符串。当您尝试更新时,您正在将价值视为一个集合,当它是一个字符串。



您可以使用 defaultdict

  combine_dict = defaultdict(set)

#首先添加MyDict
中的所有值, MyDict.iteritems():
combined_dict [int(key)]。add(value)

#然后从文件中添加值
infile = open('FileWithTheData.csv ','r')
for infile.readlines():
spl_line = line.split(',')
combined_dict [int(sp_line [0])]。update spl_line [1:])


I have a dict like this:

(100002: 'APPLE', 100004: 'BANANA', 100005: 'CARROT')

I am trying to make my dict have ints for the keys (as it does now) but have sets for the values (rather than strings as it is now.) My goal is to be able to read from a .csv file with one column for the key (an int which is the item id number) and then columns for things like size, shape, and color. I want to add this information into my dict so that only the information for keys already in dict are added.

My goal dict might look like this:

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

Starting with my dict of just key + string for item name, I tried code like this to read the extra information in from a .csv file:

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:])

Unfortunately this errors out saying AttributeError: 'str' object has no attribute 'update'. My attempts to change my dictionary's values into sets so that I can then .update them have yielded things like this: (100002: set(['A','P','L','E']), 100004: set(['B','A','N']), 100005: set(['C','A','R','O','T'])) I want to convert the values to a set so that the string that is currently the value will be the first string in the set rather than breaking up the string into letters and making a set of those letters.

I also tried making the values a set when I create the dict by zipping two lists together but it didn't seem to make any difference. Something like this MyDict = dict(zip(listofkeys, set(listofnames))) still makes the whole listofnames list into a set but it doesn't achieve my goal of making each value in MyDict into a set with the corresponding string from listofnames as the first string in the set.

How can I make the values in MyDict into a set so that I can add additional strings to that set without turning the string that is currently the value in the dict into a set of individual letters?

EDIT: I currently make MyDict by using one function to generate a list of item ids (which are the keys) and another function which looks up those item ids to generate a list of corresponding item names (using a two column .csv file as the data source) and then I zip them together.

ANSWER: Using the suggestions here I came up with this solution. I found that the section that has set()).update can easily be changed to list()).append to yield a list rather than a set (so that the order is preserved.) I also found it easier to update by .csv data input files by adding the column containing names to the FileWithTheData.csv so that I didn't have to mess with making the dict, converting the values to sets, and then adding in more data. My code for this section now looks like this:

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

解决方案

Your error is because originally your MyDict variable maps an integer to a string. When you are trying to update it you are treating the value like a set, when it is a string.

You can use a defaultdict for this:

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:])

这篇关于将dict值转换为一组,同时保留dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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