在python字典中的列表中追加值

时间:2019-06-25 12:11:50

标签: python list dictionary append

我正在尝试将值添加到词典中的列表中。我看过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']}

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分:2)

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

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