我一直遇到向已存在的键值添加值的问题。
这是我的代码:
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']}