r/learnpython•
ispywithmy

Parsing large string to dictionary

I'm currently trying to parse a file and store the contents of the file into a dictionary.

To keep it to the point, I'll use a simpler example of what the data kind of looks like...

117231:John:Doe:20:England:
206157:Jane:Smith:18:Wales:
345111:Barry:Jenkins:25:Scotland:
219854:Elvis:Parsley:70:France:

I'd like to parse this to look like...

data = {'117231':{'firstname' : 'John',
                  'lastname' : 'Doe',
                  'age': 20,
                  'location' : 'England'},
        '206157':{'firstname' : 'Jane',
                  'lastname' : 'Smith',
                  'age': 18,
                  'location' : 'Wales'},             
        ...
       }

What is the best way of achieving this? Currently I'm able to split the string into a list of each lines but I'm a bit lost after that.

(I've done something similar in JavaScript, but copying that doesn't create something pythonic looking.)

Posted Jul 31, 2017, 3:22 PM UTC

18
Loading comments…