Not able to read attribute from python dictionary
Question:
I have the below dictionary object which is created by reading each line from a log file. Each line in the log file contains data in json format as indicated by the content of “parsed_obj”. How do I get rid of this error ? I am not able to read the attribute of the dictionary even though the dictionary contains the attribute. Anything I have to do to handle the encoding?
>>> parsed_obj
{u'eventType': u'type1', u'eventDesc': u'desc1'}
>>> parsed_obj.eventType
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'eventType'
>>> type(parsed_obj)
<type 'dict'>
>>>
Answers:
Python dictionary access value using .['KEY']
.
If u want to access how u wrote like
>>> parsed_obj.eventType
then write new class. like
class NewDict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
and use it
>>> parsed_obj = NewDict(parsed_obj)
I have the below dictionary object which is created by reading each line from a log file. Each line in the log file contains data in json format as indicated by the content of “parsed_obj”. How do I get rid of this error ? I am not able to read the attribute of the dictionary even though the dictionary contains the attribute. Anything I have to do to handle the encoding?
>>> parsed_obj
{u'eventType': u'type1', u'eventDesc': u'desc1'}
>>> parsed_obj.eventType
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'eventType'
>>> type(parsed_obj)
<type 'dict'>
>>>
Python dictionary access value using .['KEY']
.
If u want to access how u wrote like
>>> parsed_obj.eventType
then write new class. like
class NewDict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
and use it
>>> parsed_obj = NewDict(parsed_obj)