Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'dict' object has no attribute 'append' Json

Tags:

python

json

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?

like image 641
KekMeister Johhny Avatar asked Nov 10 '15 22:11

KekMeister Johhny


People also ask

What does dict object has no attribute append mean?

The python AttributeError: 'dict' object has no attribute 'append' error occurs when you try to append a value in a dict object. The dict should be modified as list or the values should be added as key value in the dict object.

Has no attribute append Python?

The Python "AttributeError: 'NoneType' object has no attribute 'append'" occurs when we try to call the append() method on a None value, e.g. assignment from a function that doesn't return anything. To solve the error, make sure to only call append() on list objects.

Does Iteritems have no attribute?

Conclusion # The Python "AttributeError: 'dict' object has no attribute 'iteritems'" occurs because the iteritems() method has been removed in Python 3. To solve the error, use the items() method, e.g. my_dict. items() , to get a view of the dictionary's items.

How do I add data to a JSON in Python?

Steps for Appending to a JSON File In Python, appending JSON to a file consists of the following steps: Read the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.


2 Answers

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
like image 193
UglyCode Avatar answered Sep 22 '22 21:09

UglyCode


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

like image 36
ham_string Avatar answered Sep 22 '22 21:09

ham_string