将值添加到字典键

2024-09-27 19:13:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我在向已有的键值添加值时遇到了问题。你知道吗

这是我的密码:

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包含一对单词-AbilityAbsoluteButterflyCloud。所以AbilityAbsolute应该在同一个键下,但是我找不到一个函数可以这样做。类似于

mydict[n].append(word) 

其中n是行号。你知道吗

此外,有没有一种方法可以很容易地找到字典中的值的数目?你知道吗

电流输出=

{'a': ['ability'], 'b': ['butterfly'], 'c': ['cloud']} 

但我希望是这样

{'a': ['ability','absolute'], 'b': ['butterfly'], 'c': ['cloud']}

Tags: intxtdictionaryfilenamelowermydictwordfile
3条回答

你可以这样做

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']}

您只需将单词附加到现有键:

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语句打开您的文件,这也会在您处理完文件后关闭它。你知道吗

方案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)

相关问题 更多 >

    热门问题