How to convert text file into dict?
I have only worked with key, value pairs where
{a:"b", d:"c"}
there are only 2 values. If I have a file that has something like this
{
"personalInformationDeltaEmployee": {
"employeeID": "0",
"actualSSN": null
},
"appointmentDeltaEmployee": {
"cyberSecurityCode3": "0",
"POID": "0"
}
}
This file we are assuming is a txt file. How would I convert something like this into a dictionary?
This is what I tried:
try:
with open(filename) as f:
line_dict = {}
for part in filename:
key, value = part.split(":")
line_dict[key] = value
except Exception as e:
print e
I get need more than 1 value to unpack. I'm guessing it's mad about the extra bracket, right? What would be the best way to go about this and what are some options I can look into?
Since the data is in JSON format, you can use the json
module to parse it into a Python dictionary. In Python 2 strings aren't Unicode, so you'll also need to convert all Unicode strings in the input into that format.
Here's how to do that using a helper function. Note that the order of items in the result may not be the same as the input because in Python 2, dictionaries don't preserve the order-of-insertion.
import json
from pprint import pprint
import sys
if sys.version_info[0] > 2:
raise RuntimeError('Requires Python 2')
def unicode_convert(obj):
""" Convert unicode data to string in object and return it. """
if isinstance(obj, unicode):
obj = obj.encode()
elif isinstance(obj, list):
obj = map(unicode_convert, obj)
elif isinstance(obj, dict): # Converts contents in-place.
for key, value in obj.items(): # Copy of dict's (key, value) pairs (Py2)
del obj[key]
if isinstance(key, unicode):
key = key.encode()
if isinstance(value, (unicode, list, dict)):
value = unicode_convert(value)
obj[key] = value
return obj
with open('personal_info.json') as file:
info = json.load(file) # Parse JSON object into Python dictionary.
line_dict = {key: value for key, value in unicode_convert(info).items()}
pprint(line_dict)