6

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?

Jonah Williams
  • 20,499
  • 6
  • 65
  • 53
KekMeister Johhny
  • 141
  • 1
  • 1
  • 8
  • 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 Nov 10 '15 at 22:34
  • @CharlesDuffy appending stuff to a dict doesn't require me to say the structure – KekMeister Johhny Nov 10 '15 at 22:34
  • 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 Nov 10 '15 at 22:35
  • Even better would be explicit description of intent ("my initial data is X, I want to modify it to look like Y"). – Charles Duffy Nov 10 '15 at 22:36
  • ...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 Nov 10 '15 at 22:39
  • Does this answer your question? [Python AttributeError: 'dict' object has no attribute 'append'](https://stackoverflow.com/questions/48234473/python-attributeerror-dict-object-has-no-attribute-append) – kaya3 Feb 22 '20 at 13:44

2 Answers2

11

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
UglyCode
  • 315
  • 2
  • 12
2

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

ham_string
  • 139
  • 5