在将值添加到现有键值方面一直遇到问题。
这是我的代码:
mydict = {}
def assemble_dictionary(filename):
file = open(filename,'r')
for word in file:
word = word.strip().lower() #makes the word lower case and strips any unexpected chars
firstletter = word[0]
if firstletter in mydict.keys():
continue
else:
mydict[firstletter] = [word]
print(mydict)
assemble_dictionary('try.txt')
try.txt
包含几个词-Ability
,Absolute
,Butterfly
,Cloud
。因此Ability
和Absolute
应该在同一键下,但是我找不到能使我这样做的函数。类似于
mydict[n].append(word)
其中n是行号。
此外,有没有一种方法可以轻松地定位字典中的值数量?
当前输出=
{'a': ['ability'], 'b': ['butterfly'], 'c': ['cloud']}
但我希望成为
{'a': ['ability','absolute'], 'b': ['butterfly'], 'c': ['cloud']}
答案 0 :(得分:4)
选项1:
当检查字典中是否已存在键时,可以添加append语句。
mydict = {}
def assemble_dictionary(filename):
file = open(filename,'r')
for word in file:
word = word.strip().lower() #makes the word lower case and strips any unexpected chars
firstletter = word[0]
if firstletter in mydict.keys():
mydict[firstletter].append(word)
else:
mydict[firstletter] = [word]
print(mydict)
选项2: 您可以使用dict setDefault使用默认值初始化dict,以防不存在密钥,然后附加该项。
mydict = {}
def assemble_dictionary(filename):
file = open(filename,'r')
for word in file:
word = word.strip().lower() #makes the word lower case and strips any unexpected chars
firstletter = word[0]
mydict.setdefault(firstletter,[]).append(word)
print(mydict)
答案 1 :(得分:2)
您可以简单地将单词附加到现有键上:
def assemble_dictionary(filename):
with open(filename,'r') as f:
for word in f:
word = word.strip().lower() #makes the word lower case and strips any unexpected chars
firstletter = word[0]
if firstletter in mydict.keys():
mydict[firstletter].append(word)
else:
mydict[firstletter] = [word]
输出:
{'a': ['ability', 'absolute'], 'b': ['butterfly'], 'c': ['cloud']}
另外(与问题无关),最好使用with
语句打开文件,使用完该文件也将其关闭。
答案 2 :(得分:1)
您可以通过这种方式实现
mydict = {}
a = ['apple', 'abc', 'b', 'c']
for word in a:
word = word.strip().lower() #makes the word lower case and strips any unexpected chars
firstletter = word[0]
if firstletter in mydict.keys():
values = mydict[firstletter] # Get the origial values/words
values.append(word) # Append new word to the list of words
mydict[firstletter] = values
else:
mydict[firstletter] = [word]
print(mydict)
Outout:
{'a': ['apple', 'abc'], 'c': ['c'], 'b': ['b']}
答案 3 :(得分:0)
mydict [firstletter] = [word],替换值
由于密钥采用列表格式,请尝试
mydict[firstletter].extend(word)