user3007578
user3007578

Reputation:

Python: sorting a list by key returns error: 'string must be integers'

I've been searching to no avail and am hoping someone can point me in the right direction. I'm trying to:

My code is:

url = "http://hypem.com/playlist/tags/dance/json/1/data.js"
output = json.load(urllib.urlopen(url))
output = output.values() #convert dict to list
output = output.sort(key=itemgetter('loved_count')) #sort list by loved_count

Which gives me the following error:

output = output.sort(key=itemgetter('loved_count')) #sort list by loved_count
TypeError: string indices must be integers

Any thoughts on where I'm messing this up? Thanks in advance!

Upvotes: 7

Views: 7459

Answers (1)

falsetru
falsetru

Reputation: 369304

An item in the list is not a dictionary:

>>> import urllib
>>> import json
>>> url = "http://hypem.com/playlist/tags/dance/json/1/data.js"
>>> output = json.load(urllib.urlopen(url))
>>> for x in output.values():
...     print(type(x))
... 
<type 'dict'>
<type 'dict'>
<type 'dict'>
<type 'dict'>
<type 'dict'>
<type 'unicode'>
<type 'dict'>
....

>>> u'1.1'['loved_count']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

You can workaround by filtering out non-dictionary item(s):

>>> items = [x for x in output.values() if isinstance(x, dict)]
>>> items.sort(key=itemgetter('loved_count'))
# No error.

But, I'd rather ask the data provider what's wrong with the data because array/list is supported to contain heterogeneous data.


BTW, the code is assigning the return value of sort. sort return None; You lose the list. Remove assignment, just call sort.

Upvotes: 7

Related Questions