在Python中向字典中的键添加多个值

2024-09-29 23:28:56 发布

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

我的代码如下:

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

Tags: 代码inimportbuildrefortypecandidate

热门问题