我在向已有的键值添加值时遇到了问题。你知道吗
这是我的密码:
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']}
你可以这样做
输出:
您只需将单词附加到现有键:
输出:
另外(与问题无关)最好使用
with
语句打开您的文件,这也会在您处理完文件后关闭它。你知道吗方案1:
当检查dict中已经存在键时,可以放入append语句
方案2: 您可以使用dict setDefault以默认值初始化dict,以防键不存在,然后追加该项。你知道吗
相关问题 更多 >
编程相关推荐