Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用python在字典中的列表中追加值_Python_List_Dictionary_Append - Fatal编程技术网

用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
?Try
firsts[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