Alex
Alex

Reputation: 75

Read python dict from file

I have a file that contains multiple dictionaries as such this:

{'Segment': [{'Price': 271.03, 'Mw': 149.9, '@Number': '1'}, {'Price': 294.46, 'Mw': 106.5, '@Number': '2'}], 'Date': '2014-01-25T23', 'GenName': 60802}
{'Segment': [{'Price': 0, 'Mw': 99, '@Number': '1'}], 'Date': '2014-01-25T00', 'GenName': 57942}
{'Segment': [{'Price': 232.01, 'Mw': 10, '@Number': '1'}, {'Price': 247.31, 'Mw': 15, '@Number': '2'}, {'Price': 251.66, 'Mw': 10, '@Number': '3'}, {'Price': 257.44, 'Mw': 10, '@Number': '4'}, {'Price': 262.07, 'Mw': 9, '@Number': '5'}], 'Date': '2014-01-25T00', 'GenName': 17085}

or this:

{'Date': '2014-10-21T01', 'Segment': [{'Price': 0, '@Number': '1', 'Mw': 99}], 'GenName': 57942}
{'Date': '2014-10-21T00', 'Segment': [{'Price': 147.1, '@Number': '1', 'Mw': 10}, {'Price': 153.01, '@Number': '2', 'Mw': 15}, {'Price': 158.91, '@Number': '3', 'Mw': 10}, {'Price': 163.64, '@Number': '4', 'Mw': 10}, {'Price': 168.12, '@Number': '5', 'Mw': 9}], 'GenName': 17085}
{'Date': '2014-10-21T20', 'Segment': [{'Price': 209.22, '@Number': '1', 'Mw': 21}], 'GenName': 17541}

In other words, the order of each key is not the same within each dictionary.

My questions:
What is the best way to read this dictionaries so that I can call Date, GenName and or Segment regardless of the order? Is that possible?

Please note... This is not coming from a json file. If the dictionary is not correctly constructed, I am sure I can modify the script that generates this output.

Upvotes: 1

Views: 4526

Answers (2)

salmanwahed
salmanwahed

Reputation: 9647

Data in your file is python dictionary but not valid json object. As quots are single quot. So you can use ast.literal_eval() here. Something like this,

with open('mydict.txt', 'r') as js:
    for line in js:
        data = ast.literal_eval(line)
        print data.get('Date')

Upvotes: 2

ZdaR
ZdaR

Reputation: 22954

As you have mentioned in comments that you are creating the dictionary by yourself, so storing a dictionary in a pain .txt format is not a good idea, Python provides a library known as Pickle to preserve any object within, Using pickle is very simple.

import pickle
#Importing the module

favorite_color = { "Python": "interpreted", "C": "compiled" }
#Initializing a Dictionary (or any Python Object)

pickle.dump( favorite_color, open( "save.p", "wb" ) )
#Saving the Python object in a .p (pickle file)

#Loading the Python object from the Pickle file.
favorite_color = pickle.load( open( "save.p", "rb" ) )

You can save any Python object , nested or simple with the help of this module and later access it's value whenever needed.

Upvotes: 2

Related Questions