我一直在为现有的键值添加值时遇到问题。
这是我的代码:
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']}
最佳答案
选项1 :
当检查 dict 中已存在的键时,您可以放置 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,以防 key 不存在,然后附加该项目。
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)
关于python - 将值添加到字典键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53516437/