Python 向字典键添加值
我一直在为已有的键值添加值时遇到问题 这是我的密码:Python 向字典键添加值,python,python-3.x,Python,Python 3.x,我一直在为已有的键值添加值时遇到问题 这是我的密码: 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 = {}
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
应该在同一个键下,但是我找不到一个函数可以让我这样做。类似于
mydict[n].append(word)
其中n是行号
此外,有没有一种方法可以很容易地找到字典中的值的数目
电流输出=
{'a': ['ability'], 'b': ['butterfly'], 'c': ['cloud']}
但我希望是这样
{'a': ['ability','absolute'], 'b': ['butterfly'], 'c': ['cloud']}
mydict[firstletter]=[word],替换该值 由于密钥为列表格式,请重试
mydict[firstletter].extend(word)
您可以简单地将单词附加到现有键:
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
语句打开文件,这也会在处理完文件后将其关闭。您可以通过这种方式实现
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)
输出:
{'a': ['apple', 'abc'], 'c': ['c'], 'b': ['b']}
备选案文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,以防密钥不存在,然后追加该项
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)
你能分享一下示例输入吗?输入在代码汇编字典('try.txt')的底部,其中try.txt包含单词Ability、Absolute、Butterfly、Cloud。输出={'a':['Ability'、'a'、'b'、's'、'o'、'l'、'u'、't'、'b':['Butterfly']、'c':['Cloud']}。如果你想使用
extend
你应该给它一个列表,像.extend([word])
。我想这是因为如果for循环中的.strip()导致了该输出,我在这里尝试了其他答案,得到了相同的问题too@AvichalBettoli不,不是,我尝试了你的代码,我得到了相同的结果,但是如果你用extend([word])
替换extend([word])
,效果很好。谢谢,.append(word)现在可以工作了。不确定为什么之前没有,因为我在x之前就尝试过)