0

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!

2
  • 2
    How about city = d[0]['city']? Try looping instead Commented Sep 14, 2018 at 6:41
  • It is a list so as Arvind pointed out you should try putting the list index before the dictionary key. Commented Sep 14, 2018 at 6:44

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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']

Comments

0

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

7 Comments

Hari, thank you so much for your answer. One more thing, how can I save this output to another list? Again, thanks for your time and patience :)
I've added the code for appending the city to a list
Thanks Hari, I tried that before and I thought I wrote something wrong. I'm still getting the same error. I really don't get it :( TypeError: list indices must be integers or slices, not str
I've added another way to get a list of values. Please try that
I get an empty list as the output []. Is there a way to get the list as strings?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.