Home > Net >  How to convert text file into dict?
How to convert text file into dict?

Time:01-14

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?

CodePudding user response:

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 codecs
import json
from pprint import pprint

def unicode_convert(obj):
    """ Convert unicode data to string in object. """

    if isinstance(obj, unicode):
        return obj.encode()
    elif isinstance(obj, list):
        obj = [unicode_convert(elem) for elem in obj]
    elif isinstance(obj, dict):
        for key, value in obj.items():
            del obj[key]
            if isinstance(key, unicode):
                key = key.encode()
            if isinstance(value, unicode):
                value = value.encode()
            elif isinstance(value, (dict, list)):
                value = unicode_convert(value)
            obj[key] = value
        return obj
    else:
        return obj

with open('personal_info.json') as file:
    info = json.load(file)
    line_dict = {key: value for key, value in unicode_convert(info).items()}

pprint(line_dict)
  •  Tags:  
  • Related