繁体   English   中英

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

[英]Appending values in a list in a dictionary in python

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM