将项附加到字典中现有的/已创建的键

2024-09-28 20:53:07 发布

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

words = {'apple', 'plum', 'pear', 'peach', 'orange', 'cherry', 'quince'}

d = {}  

for x in sorted(words):  
    if x not in d:  
        d[len(x)]=x  
d[len(x)].append(x)  

print(d)  
AttributeError: 'str' object has no attribute 'append'

该程序的目标是有一个多个键,按字长(即4、5或6个字母)区分,这些键存储按字母顺序排列的值:

{4:'梨','李'5:'苹果','桃'6:'樱桃','橘子','木瓜'}

我在向密钥添加项时遇到问题。我当前得到的输出是(没有附加行):

{4:'李子',5:'桃子',6:'木瓜'}

所以它似乎在删除前面的循环条目。update和append命令返回时出错。你知道吗


Tags: inappleforlen字母cherrywordspear
2条回答

您可以使用collections.defaultdict创建一个字典,根据每个项的长度存储它们:

from collections import defaultdict
d = defaultdict(list)
words = {'apple', 'plum', 'pear', 'peach', 'orange', 'cherry', 'quince'} 
for word in words:
   d[len(word)].append(word)

final_data = {a:sorted(b) for a, b in d.items()}

输出:

{4: ['pear', 'plum'], 5: ['apple', 'peach'], 6: ['cherry', 'orange', 'quince']}

此外,itertools.groupby可用于较短的解决方案:

import itertools
words = {'apple', 'plum', 'pear', 'peach', 'orange', 'cherry', 'quince'} 
new_words = {a:sorted(list(b)) for a, b in itertools.groupby(sorted(words, key=len), key=len)}

输出:

{4: ['pear', 'plum'], 5: ['apple', 'peach'], 6: ['cherry', 'orange', 'quince']}

不能将append转换为字符串;必须从头开始创建dict值list。您还有两张支票,而不是一张:

  • 字典里有当前长度的单词吗?你知道吗
  • 给定的单词已经在列表中了吗?你知道吗

试试这个:

size = len(x)
if size not in d:  
    d[size] = [x]
else:
    d[size].append(x)

相关问题 更多 >