【问题标题】:Appending values in a list in a dictionary in python在python中的字典中的列表中附加值
【发布时间】: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


【解决方案1】:
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))

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2019-03-29
      • 2023-03-23
      • 2020-12-06
      • 2016-01-16
      • 2020-12-06
      • 1970-01-01
      • 2013-03-27
      • 2014-12-09
      相关资源
      最近更新 更多