Python 向字典中添加集合
我有一个文件Python 向字典中添加集合,python,function,dictionary,tuples,Python,Function,Dictionary,Tuples,我有一个文件random.txt,我需要从中提取每个单词,并为字典中的位置和字母编制索引。例如,它将如下:{(3,'m'):'example'}。每次有一个单词在同一位置有相同的索引字母,它只会将该单词添加到字典的值中,因此它应该是{(3,'m'):'example','salmon},而不是单独打印每个单词 这就是我所拥有的,它不会每次都把单词添加到键的值中,它只是每次都使它成为自己的值 def fill_completions(c_dict, fileObj): import str
random.txt
,我需要从中提取每个单词,并为字典中的位置和字母编制索引。例如,它将如下:{(3,'m'):'example'}
。每次有一个单词在同一位置有相同的索引字母,它只会将该单词添加到字典的值中,因此它应该是{(3,'m'):'example','salmon}
,而不是单独打印每个单词
这就是我所拥有的,它不会每次都把单词添加到键的值中,它只是每次都使它成为自己的值
def fill_completions(c_dict, fileObj):
import string
punc = string.punctuation
for line in fileObj:
line = line.strip()
word_list = line.split() #removes white space and creates a list
for word in word_list:
word = word.lower()
word = word.strip(punc) #makes lowercase and gets rid of punctuation
for position,letter in enumerate(word):
"position: {} letter: {}".format(position,letter)
my_tuple = (position,letter)
if word in my_tuple:
c_dict[my_tuple] += word
else:
c_dict[my_tuple] = word
print(c_dict)
当前您正在添加一个字符串,然后追加到该字符串 您需要放入一个元组作为值,然后添加到元组中
>>> m = dict()
>>> m['key'] = 'Hello'
>>> m['key'] += 'World'
>>> print m['key']
HelloWorld
>>>
>>> m['key'] = ('Hello',)
>>> m['key'] += ('World',)
>>> print m['key']
('Hello', 'World')
>>> # Or, if you want the value as a list...
>>> m['key'] = ['Hello']
>>> m['key'].append('World')
>>> print m['key']
['Hello', 'World']
我认为您需要将最内部循环中填充的
c_dict
代码更改为以下内容:
if my_tuple in c_dict:
c_dict[my_tuple].add(word)
else:
c_dict[my_tuple] = set([word])
下面是一个使用dict.setdefault()
的等效版本,更为简洁:
c_dict.setdefault(my_tuple, set()).add(word)