Python: sorting a list by key returns error: 'string must be integers'
Question: I've been searching to no avail and am hoping someone can point me in the
right direction. I'm trying to:

  * call a url which holds a json-formatted file
  * convert the resulting dict to a list (I don't think I need the keys that get inserted)
  * order the items in that list by a key ('loved_count')

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!


Answer: 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`.

