tags:

views:

38

answers:

3

Hey,

I'm new to python so I really don't know the language very well.

the following example was taken from here http://docs.python.org/library/json.html

>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]

what does the u mean? and how do i know which elements are available in the dictionary?

+3  A: 

It's a unicode. Iterating over the dict yields its keys:

for k in D:
  print k, D[k]
Ignacio Vazquez-Abrams
+2  A: 

Ignacio's answer a bit more verbose (no upvotes to me)

u'something' means that 'something' is a unicode string, and not for instance an ascii string. Generally text is encoded as 8-bit characters, and you need an encoding to properly interpret/display it. Unicode is 16-bit and doesn't need seperate encodings for the various locale dependent characters.

In a dictionary (enclosed by {}) the key is the part before the ":" and the value comes after.

You got a list, with elements:

  • foo, a Unicode string
  • a dictionary containing:
    • a key (unicode) "bar", and accessible through that key a list with values
      • unicode string baz,
      • None
      • a float 1.0
      • an integer 2
extraneon
+1  A: 

The python type function can be useful here.

>>> import json
>>> data = json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
>>> data
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
>>> type(data)
<type 'list'>
>>> type(data[0])
<type 'unicode'>
>>> type(data[1])
<type 'dict'>
Gregg Lind
I should haven noted that this is a 2.x series Python, where the unicode/str distinction matters.
Gregg Lind