6
votes

I have this code that adds 50 points to a user in my json file but I keep getting a 'dict' object has no attribute 'append' when trying to append new users to the users:

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)

What is the proper way of adding new objects/users to users?

2
The code here... doesn't make any sense. You're iterating over keys that are by definition already in data['users'], and then potentially trying to append them to data['users']? - Charles Duffy
@CharlesDuffy appending stuff to a dict doesn't require me to say the structure - KekMeister Johhny
You can't append a list to a dict. Not. Possible. So, we need to figure out what you actually want to do (as opposed to the impossible thing you think you want to do), and for that we need structure. - Charles Duffy
Even better would be explicit description of intent ("my initial data is X, I want to modify it to look like Y"). - Charles Duffy
...I mean, I don't even know what you expect the result of appending a list to a dict to be. If it's appending a value, how does it get the key to use? If it's a new key, where does it get a value? And if we don't know what you expect, how can we tell you how to achieve that thing? - Charles Duffy

2 Answers

11
votes

This error message has your answer.

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

 data['users'] = [dat]

If you want to append to the existing list.

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

It seems that data['users'] is a dictionary, so you can only use dictionary methods to add keys and values.