wunderkind
wunderkind

Reputation: 169

In python how do I change dictionary values from strings into dictionaries?

I have dictionary in the form :d={741178: u'{"width":37.8365,"height":150,"length":234},{"width":35.7,"height":178,"length":122}',741179: u'{"width":98.67,"height":180,"length":994},{"width":98.79,"height":167.8,"length":154.22}'}

How can I turn it into a dictionary of dictionaries? I have tried:

for k, v in d.items():
    v = ast.literal_eval(v)

But this does not work. Since each of my pseudo nested dictionaries is actually a string, how do I change their data type within the dictionary?

Upvotes: 2

Views: 236

Answers (2)

Walter Tross
Walter Tross

Reputation: 12624

You can either use ast.literal_eval() or json.loads(), the output is almost the same in this case. For JSON, you must enclose the strings in square brackets, though, because they both contain two dictionaries separated by a comma, so the only reasonable way to grab them is as a list of dictionaries. For Python literals, leaving the square brackets out (or replacing them with parentheses) causes each pair of dictionaries separated by comma to be interpreted as a 2-tuple (should be a double, but that already has a different meaning).

I personally recommend using json.loads(), because JSON is currently the most used format for data interchange in new projects. It would be best if the source of your strings could add the square brackets in order to produce valid JSON.

import ast
import json

d = {741178: u'{"width":37.8365,"height":150,"length":234},{"width":35.7,"height":178,"length":122}',
     741179: u'{"width":98.67,"height":180,"length":994},{"width":98.79,"height":167.8,"length":154.22}'}

p = {k: ast.literal_eval(v)   for k, v in d.items()}
j = {k: json.loads('['+v+']') for k, v in d.items()}

print(p)
print(j)

# {741178: ({'width': 37.8365, 'height': 150, 'length': 234}, {'width': 35.7, 'height': 178, 'length': 122}), 741179: ({'width': 98.67, 'height': 180, 'length': 994}, {'width': 98.79, 'height': 167.8, 'length': 154.22})}
# {741178: [{'width': 37.8365, 'height': 150, 'length': 234}, {'width': 35.7, 'height': 178, 'length': 122}], 741179: [{'width': 98.67, 'height': 180, 'length': 994}, {'width': 98.79, 'height': 167.8, 'length': 154.22}]}

As you can see, the only difference is ( )[ ]

Upvotes: 2

user_D_A__
user_D_A__

Reputation: 460

I have corrected the json and removed un-necessary double quotes and commas If you want to have dictionary as values you have to have the values as an array of dictionaries.

import json    
d={741178:
       u'{"width":37.8365,"height":150,"length":234},'
       u'{"width":35.7,"height":178,"length":122}',
   741179: u'{"width":98.67,"height":180,"length":994},'
           u'{"width":98.79,"height":167.8,"length":154.22}'

   }
for key, value in d.items():
    d[key]= json.loads('['+value+']')
print(d)

Upvotes: 0

Related Questions