【发布时间】:2019-11-07 06:37:35
【问题描述】:
我正在尝试将值添加到字典内的列表中。我查看了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' 对象没有属性 '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']}
【问题讨论】:
-
firsts[fn] = full...? -
试试
firsts[fn] =full,因为firsts是一本字典。 -
@ArkistarvhKltzuonstev “尝试”是什么意思?那行是问题。
-
似乎是
defaultdict的一个很好的用例
标签: python list dictionary append