python - 向字典键添加值

标签 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]
       if firstletter in mydict.keys():
           continue
       else:
           mydict[firstletter] = [word]

   print(mydict)

assemble_dictionary('try.txt')

try.txt 包含几个词 - Ability , Absolute, Butterfly, 。所以 AbilityAbsolute 应该在同一个键下,但是我找不到可以让我这样做的函数。类似于

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/

相关文章:

python - BeautifulSoup 模块未检测到任何标签

python - 为什么不调用 __instancecheck__?

python - 在列表上迭代两次的正确方法?

python - 从 DM.de 抓取客户评论

python - 如果我有每日值,如何使用 Pandas 计算每周累计值总和?

python - Airflow :从上游任务访问模板字段

python - 计算二维数据点数组的最高密度区间 (HDI)

python - 如何在不解析整个文件的情况下获取树的根?

python - Tkinter Linux 版本 "<Control-Shift-u>"

mysql - Django 模型 ID 被 GenericForeignKey 的 ID 覆盖