'str' object has no attribute '__dict__' - python

I want to serialize a dictionary to JSON in Python. I have this 'str' object has no attribute 'dict' error. Here is my code...
from django.utils import simplejson
class Person(object):
a = ""
person1 = Person()
person1.a = "111"
person2 = Person()
person2.a = "222"
list = {}
list["first"] = person1
list["second"] = person2
s = simplejson.dumps([p.__dict__ for p in list])
And the exception is;
Traceback (most recent call last):
File "/base/data/home/apps/py-ide-online/2.352580383594527534/shell.py", line 380, in post
exec(compiled_code, globals())
File "<string>", line 17, in <module>
AttributeError: 'str' object has no attribute '__dict__'

How about
s = simplejson.dumps([p.__dict__ for p in list.itervalues()])

What do you think [p.__dict__ for p in list] does?
Since list is not a list, it's a dictionary, the for p in list iterates over the key values of the dictionary. The keys are strings.
Never use names like list or dict for variables.
And never lie about a data type. Your list variable is a dictionary. Call it "person_dict` and you'll be happier.

You are using a dictionary, not a list as your list, in order your code to work you should change it to a list e.g.
list = []
list.append(person1)
list.append(person2)

Related

Getting the TypeError: 'list' object is not callable in Python

class Student:
def __init__(self,first,last,id):
self._first_name = first
self._last_name = last
self._id_number = id
self._enrolled_in = []
def enroll_in_course(self,course):
self._enrolled_in.append(course)
return self._enrolled_in()
s1 = Student("kathy","lor","323232")
s1.enroll_in_course("hello")
print(s1._enrolled_in)
In the code above, i am getting the error as:
Traceback (most recent call last):
File "main.py", line 14, in
s1.enroll_in_course("hello") File "main.py", line 10, in enroll_in_course
return self._enrolled_in()
TypeError: 'list' object is not callable
I am trying to solve the error, but unable to do so. Can anybody help me here.
You have defined self._enrolled_in but you're adding it to self.enrolled_in
Missed the underscore (self._enrolled_in.append)
You have called the attribute _enrolled_in in your __init__() method. In the enroll_in_course() method you're trying to append to enrolled_in which does not exist. So try by adding the underscore in front.
You are missing an _ in the appended statement. You should write self._enrolled_in.append(course) on your enroll_in_course method.

Dict in AutoProxy object from remote Manager is not subscriptable

This is my code.
from multiprocessing.managers import BaseManager
from threading import Thread
def manager1():
my_dict = {}
my_dict['key'] = "value"
print(my_dict['key']) #this works
class SyncManager(BaseManager): pass
SyncManager.register('get_my_dict', callable=lambda:my_dict)
n = SyncManager(address=('localhost', 50001), authkey=b'secret')
t = n.get_server()
t.serve_forever()
def get_my_dict_from_the_manager():
class SyncManager(BaseManager): pass
SyncManager.register('get_my_dict')
n = SyncManager(address=('localhost', 50001), authkey=b'secret')
n.connect()
my_dict = n.get_my_dict()
return my_dict
thread1 = Thread(target=manager1)
thread1.daemon = True
thread1.start()
my_dict = get_my_dict_from_the_manager()
print(my_dict.keys()) #this works
print(my_dict['key']) #DOES NOT WORK
On the last line of the script, I try to access a value in the dictionary my_dict by subscripting with a key. This throws an error. This is my terminal output:
value
['key']
Traceback (most recent call last):
File "/home/magnus/PycharmProjects/docker-falcon/app/so_test.py", line 31, in <module>
print(my_dict['key'])
TypeError: 'AutoProxy[get_my_dict]' object is not subscriptable
Process finished with exit code 1
It seems the AutoProxy object sort of behaves like the dict it is supposed to proxy, but not quite. Is there a way to make it subscriptable?
The problem is that the AutoProxy object does not expose the __getitem__ method that a dict normally has. An answer to my similar question allows you to access items by their key: simply replace print(my_dict['key']) with print(my_dict.get('key'))

“TypeError: 'unicode' object does not support item assignment” in dicts when scraping via scrapy pipeline

I'm trying to build a dictionary of keywords and put it into a scrapy item.
'post_keywords':{1: 'midwest', 2: 'i-70',}
The point is that this will all go inside a json object later on down the road. I've tried initializing a new blank dictionary first, but that doesn't work.
Pipeline code:
tag_count = 0
for word, tag in blob.tags:
if tag == 'NN':
tag_count = tag_count+1
nouns.append(word.lemmatize())
keyword_dict = dict()
key = 0
for item in random.sample(nouns, tag_count):
word = Word(item)
key=key+1
keyword_dict[key] = word
item['post_keywords'] = keyword_dict
Item:
post_keywords = scrapy.Field()
Output:
Traceback (most recent call last):
File "B:\Mega Sync\Programming\job_scrape\lib\site-packages\twisted\internet\defer.py", line 588, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "B:\Mega Sync\Programming\job_scrape\cl_tech\cl_tech\pipelines.py", line215, in process_item
item['post_noun_phrases'] = noun_phrase_dict
TypeError: 'unicode' object does not support item assignment
It SEEMS like pipelines behave weirdly, like they don't want to run all the code in the pipeline UNLESS all the item assignments check out, which makes it so that my initialized dictionaries aren't created or something.
Thanks to MarkTolonen for the help.
My mistake was using the variable name 'item' for more than two things.
This works:
for thing in random.sample(nouns, tag_count):
word = Word(thing)
key = key+1
keyword_dict[key] = word
item['post_keywords'] = keyword_dict

Python: TypeError: 'str' object is not callable Rating System

When I run this code:
def printPredictions(matches):
pPredictionTable = PrettyTable()
pPredictionTable.field_names = ["Player 1", "Player 2", "Difference", "Winner"]
for match in matches:
p1 = match['teamA']
p2 = match['teamB']
if match['aBeatb'] == True:
pPredictionTable.add_row([match['teamA'], match['teamB'], match['difference'], p1])
else:
pPredictionTable.add_row([match['teamA'], match['teamB'], match['difference'], p2])
print(pPredictionTable)
printPredictions(pmatches)
I get this error:
Traceback (most recent call last):
File "C:\Users\ericr_000\Desktop\PyDev\NPA-2-Rating-System\Rankings.py", line 645, in <module>
printPredictions()
TypeError: 'str' object is not callable
I have pmatches as a separate dictionary, and I don't have the coding skills to fix this issue. (Line 145 is printPredictions(pmatches)
If you're getting 'str' object is not callable when you try to call printPredictions, that means that by the time your program reaches line 645, the name printPredictions was reassigned to a string. Somewhere in your code you have something like
printPredictions = someStringValueGoesHere
You should choose a different name for that variable, or delete the line entirely.
foobar = someStringValueGoesHere

Getting 'NoneType' object has no attribute '__getitem__' on an empty list

Here's the snippet of my function:
def getFriends(screen_name, user_id=0):
friends = []
twitter = login()
if screen_name:
response = make_twitter_request(twitter.friends.ids, screen_name=screen_name, count=5000)
else:
response = make_twitter_request(twitter.friends.ids, user_id=user_id, count=5000)
friends += response['ids']
for i in range(10):
cursor = response['next_cursor']
if(cursor!=0):
response = make_twitter_request(twitter.friends.ids, screen_name=screen_name, count=5000)
friends += response['ids']
print friends
return friends
I've confirmed that response is not empty and that friends is indeed the empty list, yet when I try to do friends += response['ids'] I get the traceback:
Traceback (most recent call last):
File "hw2.py", line 75, in <module>
makeGraph('katyperry')
File "hw2.py", line 67, in makeGraph
myList = getFriends(None, user_id=user_id)
File "hw2.py", line 30, in getFriends
friends += response['ids']
TypeError: 'NoneType' object has no attribute '__getitem__'
Anyone has any idea why? Is it something really obvious that I"m missing?
Edit: here's the response, I've cut out the list a bit, but this is generally what you get
{u'next_cursor_str': u'1319524982440652073', u'previous_cursor': 0, u'ids': [764777174, 201407468, 354264328, 84230267, 19777398, 822447170, 1969597074, 215511591, 1072197655, 93090464, 1895856553, 2148169409, 209708391, 441902035, 32469566, 158314798, 59013314, 90368637, 1205971568, 2218722350, 26334324, 150459410, 188553447, 606580718, 16411682, 404747151, 50127057, 433057142, 387713711, 343649316, 1066545259, 1210138951, 1178700428, 325652049, 265234804, 176538071, 1671978253, 400541768, 111718180, 2320113704, 317262708, 716735610, 2299884229, 2310952307, 278721743, 172989401, 745672010, 289403411, 569259066, 704350131, 380131462, 1353007663, 551726304, 1129951819, 1196832457, 572515555, 1699140998, 238251656, 2183313640, 2271781134, 239867327, 283216570, 2187940812, 213011297, 1876144244, 26968935, 1655642300, 272308935, 1571227472, 325651498, 998220847, 550442329, 1240472737, 24607504, 64080354, 34774807, 211151198, 265495165, 44444328, 2159461650, 186888760, 263960873, 244490281, 1470947208, 431145806, 407064130, 133880286], u'next_cursor': 1319524982440652073, u'previous_cursor_str': u'0'}
You set response with:
response = make_twitter_request(twitter.friends.ids, screen_name=screen_name, count=5000)
and make_twitter_request() returned None.
response must be None. __getitem__ is the Python magic method for overloading [] (that is to say, a[1] calls a.__class__.__getitem__(1)). You're getting this error because you're still using 2.x, if you upgraded to the newer 3.x series (which is incompatible in some minor ways, mostly a cleanup of the language), you get the friendlier TypeError: 'NoneType' object is not subscriptable.
There is nothing else on that line that could be causing that error, so unless make_twitter_request is returning some funky class that has a weird __getitem__, response must be None.

Categories

Resources