Accessing values from a Unicode dictionary in Python

Writing by on Saturday, 8 of November , 2014 at 10:05 pm

I was running into several errors while accessing a dictionary persisted in MongoDB as JSON (with Unicode) until I found this post on stackoverflow.com.

TypeError: string indices must be integers, not unicode

So basically the way to workaround the problem is as follows:

import json, ast

# You would assume this would work ...
somekey_val = dict[SOME_KEY]

# but due to frustrations with unicode in python handle it
try:
    somekey_val = ast.literal_eval(dict[SOME_KEY])
except Exception, e:
    print 'unicode conversion not needed for some_key'

# do regular processing from here on
process( somekey_val )

Leave a comment

Category: Python

No Comments

No comments yet.

Leave a comment

You must be logged in to post a comment.

Shivdev Kalambi's Blog

Shivdev Kalambi is a Software Development Manager, previously a Principal Software Engineer at ArcSight/HP. With over 16 years' experience in software development, he's worked on several technologies and played different roles and contributed to all phases of projects. Non-tech activies include Ping-pong, Rock Climbing and Yoga at PG, Golf, Skiing, Swimming & a beer enthusiast.