用python在字典中的列表中追加值
我正在尝试向字典中的列表添加值。我已经查看并尝试了用python在字典中的列表中追加值,python,list,dictionary,append,Python,List,Dictionary,Append,我正在尝试向字典中的列表添加值。我已经查看并尝试了追加,但是我得到了一个错误 代码: 错误: AttributeError:“str”对象没有属性“append” 期望输出: {'Shelba': ['Shelba Barthel', 'Shelba Crowley', 'Shelba Fernald', 'Shelba Odle', 'Shelba Fry'],'David': ['David Joyner', 'David Zuber'], 'Brenton': ['Brenton Joyn
追加
,但是我得到了一个错误
代码:
错误:
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']}
创建列表时,将立即用字符串替换它。 尝试: 而不是
if fn in firsts:
firsts[fn].append(full)
else:
firsts[fn] = []
firsts[fn] = full
firsts[fn]=full
?Tryfirsts[fn]=full
因为firsts
是一本字典。@ArkistarvhKltzuonstev“Try”是什么意思?这一行就是问题所在。对于defaultdict
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