0
votes

I'm a python newbie and I need to read and manipulate elements from a json file, but I keep getting errors and I have no idea how to move forward. This is my code:

import json 
with open('file.txt', 'r') as json_data:
    d = json.load(json_data)

An example of the dataset:

[
    {
        'id': 1,
        'name': 'a',
        'city': 'Paris'
    },
    {
        'id': 2,
        'name': 'b',
        'city': 'Mons'
    },
    {
        'id': 3,
        'name': 'c.',
        'city': 'Leuven'
    }
]

When I try to get only id or name, I get this error:

city = d['city']

TypeError Traceback (most recent call last)

in ()

----> 1 city = d['city']

TypeError: list indices must be integers or slices, not str

Then I tried this:

city = d[:]['city']

TypeError Traceback (most recent call last)

in () ----> 1 city = d[:]['city']

TypeError: list indices must be integers or slices, not str

Any ideas? Thanks!

3
How about city = d[0]['city']? Try looping instead - user2575725
It is a list so as Arvind pointed out you should try putting the list index before the dictionary key. - Ninad Gaikwad

3 Answers

1
votes

You more likely don't want to know the array index of the element you are looking for.

With some pythonic flavor, you can create tuples with a list comprehension like this:

arr = [(dict['id'], dict['city']) for dict in d]

The output would be

[(1, 'Paris'),
(2, 'Mons'),
(3, 'Leuven')]

Then, you have the possibility to get only specific items in your tuples if needed.

Ex:

arr = [(dict['id'], dict['city']) for dict in d if 's' in dict['city']]

which would return id and name for every entry that contain 's' in the city property.

0
votes

As this is a dictionary within a list you must provide a list index before calling value by the key. This should work:

dict = d[0]
city = dict['city']

Or you can simply use:

city = d[0]['city']
0
votes

You can write a loop to go through each object

final=[]
for obj in d:
    final.append(obj['city'])

Or you can try using this

final = [obj['city'] for obj in d]

Or if you only need the first value then

print(d[0]['city'])

Output

'Paris'

Since your data is a list of dictionaries, you'll have to use the index value to get the data in the dictionary