Convert unicode string dictionary into dictionary in python

PythonUnicodeDictionary

Python Problem Overview


I have unicode u"{'code1':1,'code2':1}" and I want it in dictionary format.

I want it in {'code1':1,'code2':1} format.

I tried unicodedata.normalize('NFKD', my_data).encode('ascii','ignore') but it returns string not dictionary.

Can anyone help me?

Python Solutions


Solution 1 - Python

You can use built-in ast package:

import ast

d = ast.literal_eval("{'code1':1,'code2':1}")

Help on function literal_eval in module ast:

>literal_eval(node_or_string) > >Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

Solution 2 - Python

You can use literal_eval. You may also want to be sure you are creating a dict and not something else. Instead of assert, use your own error handling.

from ast import literal_eval
from collections import MutableMapping

my_dict = literal_eval(my_str_dict)
assert isinstance(my_dict, MutableMapping)

Solution 3 - Python

EDIT: Turns out my assumption was incorrect; because the keys are not wrapped in double-quote marks ("), the string isn't JSON. See here for some ways around this.

I'm guessing that what you have might be JSON, a.k.a. JavaScript Object Notation.

You can use Python's built-in json module to do this:

import json
result = json.loads(u"{'code1':1,'code2':1}")   # will NOT work; see above

Solution 4 - Python

I was getting unicode error when I was reading a json from a file. So this one worked for me.

import ast
job1 = {}
with open('hostdata2.json') as f:
  job1= json.loads(f.read())

f.close()

#print type before converting this from unicode to dic would be <type 'unicode'>

print type(job1)
job1 =  ast.literal_eval(job1)
print "printing type after ast"
print type(job1)
# this should result <type 'dict'>

for each in job1:
 print each
print "printing keys"
print job1.keys()
print "printing values"
print job1.values()

Solution 5 - Python

You can use the builtin eval function to convert the string to a python object

>>> string_dict = u"{'code1':1, 'code2':1}"
>>> eval(string_dict)
{'code1': 1, 'code2': 1}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSudhir AryaView Question on Stackoverflow
Solution 1 - PythonagaView Answer on Stackoverflow
Solution 2 - PythonpyrospadeView Answer on Stackoverflow
Solution 3 - PythonAlastair IrvineView Answer on Stackoverflow
Solution 4 - PythonMeena RajaniView Answer on Stackoverflow
Solution 5 - PythonAli-Akber SaifeeView Answer on Stackoverflow