gwydion93
gwydion93

Reputation: 1923

Getting a dictionary item from a list in a dictionary

Suppose I have a dictionary, that then has a list of dictionaries within it:

cslfJson = {'displayFieldName': 'CSLF_ID',
            'features': [{'attributes': {'OBJECTID': '13000', 'CSLF_ID': '08123', 'Area_SF': '5431'},
                         {'attributes': {'OBJECTID': '12000', 'CSLF_ID': '08137', 'Area_SF': '2111'}}]}

How would I call OBJECTID in a print statement? WIle I can print something like this

print(cslfJson['features'][1]['attributes']['OBJECTID'])

I am trying to print both OBJECTID's like this:

for index in cslfJson['features']: 
    print(cslfJson['features'][index]['attributes']['OBJECTID'])

The above throws a TypeError: list indices must be integers or slices, not dict error, so I am confused on the correct syntax.

Upvotes: 0

Views: 38

Answers (2)

John La Rooy
John La Rooy

Reputation: 304255

print(*x['attributes']['OBJECTID'] for x in cslfJson['features']) 

Upvotes: 1

mattbornski
mattbornski

Reputation: 12553

You are iterating over the contents of the list, not the indices, so index is itself the dictionary. There are several options to iterate over the indices, or you could use the dictionary that you're being given instead:

for subdictionary in cslfJson['features']: 
    print(subdictionary['attributes']['OBJECTID'])

Upvotes: 2

Related Questions