【问题标题】:Append items to existing/created keys in a dictionary [duplicate]将项目附加到字典中现有/创建的键[重复]
【发布时间】:2018-07-02 17:44:35
【问题描述】:
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: '木瓜'}

所以它似乎正在删除以前的循环条目。更新和追加命令返回错误。

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以使用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']}
    

    【讨论】:

    • 出色地使用了groupby。我不喜欢为final_data 创建的新字典和新子列表,当就地排序会像for sublist in d.values(): sublist.sort() 那样进行时。预先排序也可以像for word in sorted(words): 一样工作。 (当然,这都是偏好。关于 dict 理解的一个好处是您不再拥有 defaultdict。)
    • @StevenRumbalski 我也更喜欢groupby :) 然而,SO 上的一些用户似乎更喜欢defaultdict,所以我认为最好提供一个同时利用两者的解决方案。
    【解决方案2】:

    你不能append 到一个字符串;你必须从一开始就让你的dict值lists。您还有 两个 检查,而不是一个:

    • 字典中是否有当前长度的单词?
    • 给定的单词是否已经在列表中?

    试试这个:

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

    【讨论】:

    • 别忘了else: d[len(x)].append(x)
    • 除了错误消息之外,另一件事是 OP 正在检查 strx 值是否不在 d 上,而不是 x 的长度上。这反过来又将 len(x) 的值重新分配给一个新列表,因为 x 永远不会作为键存在
    • 感谢扩展和代码审查。
    • 我的错误——当我添加......好吧,我重新输入了整个列表并使用了错误的书挡。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 2017-12-17
    相关资源
    最近更新 更多