Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

So I have the list of objects from an API which looks like this:

{

    "1": {

        "artist": "Ariana Grande",

        "title": "Positions"

    },

    "2": {

        "artist": "Luke Combs",

        "title": "Forever After All"

    },

    "3": {

        "artist": "24kGoldn Featuring iann dior",

        "title": "Mood"

    },

}

I was wondering how do I run the for loop to access each item.

def create_new_music_chart(data_location):

    with open(data_location, 'r') as json_file:

        data = json.load(json_file)

for song in data:

    print(song)

 

Returns:

```

1

2

3

but when I try doing this to the print artist, it doesn't work:

for song in data:

    print(song[artist])

Result:

TypeError: string indices must be integers

1 Answer

0 votes
by (36.8k points)

The song is a key in the dictionary. If you want to get an artist, you must look up the key song in the dictionary data, and the artist should be a string:

for song in data:

    # song is "1"

    # data[song] is {"artist": "Ariana Grande", "title": "Positions"}

    print(data[song]["artist"])

Want to be a master in Data Science? Enroll in this Data Science Courses

Browse Categories

...