phicon
phicon

Reputation: 3617

Python Print all from json

I am able to use the following code to extract one of the artist of all the artists in the list.

print (data['topartists']['artist'][0]['name'])

Now i would like the print to return all the artists names.

I would assume using for:

for i in data:
    print (data['topartists']['artist'][i]['name'])

However this results in the error: TypeError: list indices must be integers, not unicode

What should i add to print all the artists?

Upvotes: 2

Views: 183

Answers (2)

YinglaiYang
YinglaiYang

Reputation: 91

You already got a good answer, so I will just give a little bit of background information.

The problem here is that

for i in data: ...

gives you a loop, where i are the individual elements in data and not the indices like i=range(0,len(data)) as you probably expected.


Solution for your code:

Solution with i being a counter that goes through the list (C++/Java-style):

for i in range(0,len(data)):
    print (data['topartists']['artist'][i]['name'])

Solution that is closer to normal Python notation (what lnxmen proposed):

for artist in data['topartists']['artist']:
    print (artist['name'])

In this more pythonic solution, the loop lets you do something with each single element in the list (for artist in list_of_artists), instead of giving you a counter like i.

Upvotes: 1

mwarzynski
mwarzynski

Reputation: 304

You should iterate artists, not the data itself.

for i in data['topartists']['artist']:
    print (i['name'])

Upvotes: 1

Related Questions