【问题标题】:Adding multiple values to a key in dictionary in Python在 Python 中向字典中的键添加多个值
【发布时间】:2018-02-10 07:22:05
【问题描述】:

我的代码如下:

import re
import os
dict = {}
rpm_list = ['rpm1', 'rpm2', 'rpm3']
build_type = 'candidate'

for rpm in rpm_list:
    repo_path = '/product/Esoteric/candidate'
    if re.search(build_type, repo_path):
        if build_type in dict:
            dict[build_type].append(rpm)
        else:
            dict[build_type] = ''
    else:
        print ("None")

for key in dict:
    print (dict[key])

我尝试过查看其他帖子并使用 setdefault 方法。帮助不大。 代码失败并出现以下错误:

dict[build_type].append(rpm)
AttributeError: 'str' object has no attribute 'append'

有人可以帮忙吗? 预期的输出是:(也会有其他键。)

{'candidate': ['rpm1', 'rpm2', 'rpm3']}

【问题讨论】:

  • append 用于追加新键.. 不用于值追加。你的预期输出是什么。
  • 如何在此处将值附加到现有键?
  • dict[build_type] = '' 你将它设置为一个空字符串(字符串没有附加)......你希望它等于一个列表,对吧?
  • 提供输入和预期输出。
  • 谢谢@abccd .. 它有帮助。我希望它等于列表。那里的错误。非常感谢

标签: python


【解决方案1】:

使用defaultdict:

from collections import defaultdict
dct = defaultdict(list)
# name changed to dct as dict is builtin

# other stuff omitted
if re.search(build_type, repo_path):
    dct[build_type].append(rpm)  # any missing keys will generate a list

【讨论】:

    猜你喜欢
    • 2020-06-10
    • 1970-01-01
    • 2018-05-27
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    相关资源
    最近更新 更多