我在向现有键值添加值时遇到了问题。
这是我的代码:
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
, 云
。所以 Ability
和 Absolute
应该在同一个键下,但是我找不到可以让我这样做的函数。类似于
mydict[n].append(word)
其中 n 是行号。
还有,有没有办法方便地定位字典中值的个数?
当前输出 =
{'a': ['ability'], 'b': ['butterfly'], 'c': ['cloud']}
但我希望它是
{'a': ['ability','absolute'], 'b': ['butterfly'], 'c': ['cloud']}
最佳答案
选项 1:
当检查key已经存在于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,以防键不存在,然后附加该项目。
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/