在python词典的列表中追加值

2024-09-27 21:32:26 发布

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

我正在尝试向字典中的列表添加值。我已经看过this并尝试过append,但是我得到了一个错误。你知道吗

代码:

def name_counts(x):
    firsts = {}
    for full in x:
        part = full.split()
        fn = part[0]
        if fn in firsts:
            firsts[fn].append(full)
        else:
            firsts[fn] = []
            firsts[fn] = full
    return(firsts)


name_list = ["David Joyner", "David Zuber", "Brenton Joyner",
             "Brenton Zuber", "Nicol Barthel", "Shelba Barthel",
             "Shelba Crowley", "Shelba Fernald", "Shelba Odle",
             "Shelba Fry", "Maren Fry"]
print(name_counts(name_list))

错误:

AttributeError: 'str' object has no attribute 'append'

期望输出:

{'Shelba': ['Shelba Barthel', 'Shelba Crowley', 'Shelba Fernald', 'Shelba Odle', 'Shelba Fry'],'David': ['David Joyner', 'David Zuber'], 'Brenton': ['Brenton Joyner', 'Brenton Zuber'], 'Maren': ['Maren Fry'], 'Nicol': ['Nicol Barthel']}

Tags: name错误fullfndavidappendfirstsnicol
2条回答
def name_counts(x):
firsts = {}
for full in x:
    part = full.split()
    fn = part[0]
    if fn not in firsts:
        firsts[fn] = []

    firsts[fn].append(full)
return(firsts)


name_list = ["David Joyner", "David Zuber", "Brenton Joyner",
         "Brenton Zuber", "Nicol Barthel", "Shelba Barthel",
         "Shelba Crowley", "Shelba Fernald", "Shelba Odle",
         "Shelba Fry", "Maren Fry"]
print(name_counts(name_list))

创建列表时,会立即用字符串替换它。 尝试:

if fn in firsts:
    firsts[fn].append(full)
else:
    firsts[fn] = [full]

而不是

if fn in firsts:
    firsts[fn].append(full)
else:
    firsts[fn] = []
    firsts[fn] = full

相关问题 更多 >

    热门问题