开发者

Python how to handle # in a dictionary

I've g开发者_Go百科ot some json from last.fm's api which I've serialised into a dictionary using simplejson. A quick example of the basic structure is below.

{
  "artist": "similar": {
    "artist": {
      "name": "Blah",
      "image": [{
        "#text": "URLHERE",
        "size": "small"
      }, {
        "#text": "URLHERE",
        "size": "medium"
      }, {
        "#text": "URLHERE",
        "size": "large"
      }]
    }
  }
}

Any ideas how I can access the image urls of various different sizes?

Thanks,

Jack


Python does not have any problem with # in strings used as dict keys.

>>> import json
>>> j = '{"#foo": 6}'
>>> print json.loads(j)
{u'#foo': 6}
>>> print json.loads(j)[u'#foo']
6
>>> print json.loads(j)['#foo']
6

There are, however, problems with the JSON you post. For one, it isn't valid (perhaps you're missing a couple commas?). For two, you have a JSON object with the same key "image" three times, which cannot coexist and do anything useful.


In Javascript, these two syntaxes are equivalent:

o.foo
o['foo']

In Python they are not. The first gives you the foo attribute, the second gives you the foo key. (It's debatable whether this was a good idea or not.) In Python, you wouldn't be able to access #text as:

o.#text

because the hash will start a comment, and you'll have a syntax error.

But you want

o['#text']

in any case.


You can get what you want from the image list with a list comprehension. Something like

desired = [x for x in images if minSize < x['size'] < maxSize]

Here, images would be the list of dicts from the inner level of you data structure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜