简体   繁体   中英

Accessing dictionary elements in python

I working with some twitter data, I get the data by monitoring the twitter stream, then I save the results in a *.txt file

I´m trying to manipulate this txt file with python, for that I use the json.loads() instruction, with every line in the file where the twitter stream result was saved, in that way I got every file line as an json object.

for line in twitter_file
    data = json.loads(line)

The json object (one json object for one file line) is loaded in a variable called "data"

Everyting is working there, when I try to access an element in the "data" json object I can do it, for example, if I can see the place element, I can do it with data["place"], so I got this:

"place":{
            "id":"00a961d91f76dde8",
            "url":"https:\/\/api.twitter.com\/1.1\/geo\/id\/00a961d91f76dde8.json",
            "place_type":"city",
            "name":"Capital - Corrientes",
            "full_name":"Capital - Corrientes",
            "country_code":"AR",
            "country":"Argentina",
            "contained_within":[]
            }

I can access the "place" element, if I execute print data["place"] , I can see the text displayed above.

The problem comes when I'm trying to access an specific key in place dictionary,

I tried to do it in this way

data["place"]["place_type"]

I'm waiting to get the "city" value as result, but I can not do it, I get the following error: TypeError: "NoneType" object has no attribute '__getitem__'

I also tried other ways to display the key-value pairs with the following:

for key,value in data["data"].items()
    print key

But I don't get the result

I also tried with

print data["place"].keys()[0]

To get printed the first element, but It doesn't work either. I got the following error message: AttributeError: 'NoneType' object has no attribute 'keys'

It seems that my data["place"] is not being considered as a dictionary by Python, that's what I guess, but I'm not sure, I'm pretty new at Python, so any comment will be very helpful for me.

You are looping over a file and loading each line as JSON. Some of those JSON objects have place set to a dictionary, others have it set to None .

Whenever you just loaded a line with the value associated with the place key set to None , you'll get the AttributeError exception.

You need to test for this first:

place = data['place']
if place is not None:
    print place['place_type']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM