【问题标题】:'dict' object has no attribute 'append' Json'dict' 对象没有属性 'append' Json
【发布时间】:2016-02-11 23:05:22
【问题描述】:

我的这段代码在我的 json 文件中为用户添加了 50 分,但在尝试将新用户附加到用户时,我不断收到 'dict' object has no attribute 'append'

def updateUsers(chan):
    j = urllib2.urlopen('http://tmi.twitch.tv/group/user/' + chan + '/chatters')
    j_obj = json.load(j)
    with open('dat.dat', 'r') as data_file:
        data = json.load(data_file)
        for dat in data['users']:
            if dat in j_obj['chatters']['moderators'] or j_obj['chatters']['viewers']:
                data['users']['tryhard_cupcake']['Points'] += 50
            else:
                data['users'].append([dat]) # append doesn't work here
    with open('dat.dat', 'w') as out_file:
        json.dump(data, out_file)

users 添加新对象/用户的正确方法是什么?

【问题讨论】:

  • 这里的代码......没有任何意义。您正在遍历data['users'] 中已经定义的键,然后可能尝试将它们附加到data['users']
  • @CharlesDuffy 将内容附加到 dict 不需要我说出结构
  • 不能将列表附加到字典。不是。可能的。因此,我们需要弄清楚你实际上想要做什么(而不是你认为你想要做的不可能的事情),为此我们需要结构。
  • 最好是对意图的明确描述(“我的初始数据是 X,我想修改它看起来像 Y”)。
  • ...我的意思是,我什至不知道您期望将列表附加到 dict 的结果是什么。如果它附加一个值,它如何获得要使用的密钥?如果它是一个新的键,它在哪里得到一个值?如果我们不知道您的期望,我们如何告诉您如何实现这一目标?

标签: python json


【解决方案1】:

这条错误信息有你的答案。

https://docs.python.org/2/tutorial/datastructures.html#dictionaries

 data['users'] = [dat]

如果要追加到现有列表。

templist = data['users']
templist.extend(dat)
data['users'] = templist

【讨论】:

  • 您的代码覆盖旧数据而不是添加新数据?
  • 您应该使用列表来追加 .字典有一个键值对,键应该是唯一的。
【解决方案2】:

看来data['users']是字典,所以只能使用字典的方法来添加键值。

【讨论】:

    猜你喜欢
    • 2019-03-11
    • 1970-01-01
    • 2019-03-31
    • 2018-06-22
    • 2020-11-07
    • 2020-10-16
    • 2021-05-26
    • 2020-12-08
    • 2019-11-16
    相关资源
    最近更新 更多