Question

In my app I'm connecting to a server which returns some json style unicode string resembling dictionary of dictionaries. As a result I'd like to get one leveled dictionary with id as a key and unicode value like this :

{'1': u'autos','3': u'cities'}

So I load the response with built in json module :

>>> jsonData = json.loads(data)
>>> jsonData
{u'1': {u'id': u'1', u'name': u'autos'}, u'3': {u'id': u'3', u'name': u'cities'}, u'2': {u'id': u'2', u'name': u'business'},}
>>> type(jsonData)
<type 'dict'>

You can see the returned object here. Then I should decompose it to get rid of the parent dictionary. And finally encode the id's. I've found two methods how to do the encoding. One :

>>> import unicodedata
>>> unicodedata.normalize('NFKD', data).encode('ascii','ignore')

and second:

>>> data.encode('ascii','ignore')

How I should do this task, especially the decomposition ?

Was it helpful?

Solution

This should work:

outputdata = {}
for id, stuff in jsonData.iteritems():
    outputdata[id.encode("ascii")] = stuff[u"name"]

You could also use a generator expression, as in dugres' answer.

OTHER TIPS

decomp=dict((v['id'], v['name']) for v in jsondata.values())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top