从文件中读取 python 字典

Read python dict from file

我有一个包含多个词典的文件,例如:

{'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}

或者这个:

{'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}

换句话说,每个字典中每个键的顺序是不一样的。

我的问题:
阅读此词典的最佳方式是什么,以便我可以调用 Date、GenName 和/或 Segment,而不管顺序如何?这可能吗?

请注意...这不是来自 json 文件。如果字典构建不正确,我相信我可以修改生成此输出的脚本。

您文件中的数据是 python 字典,但不是有效的 json 对象。因为引号是单引号。所以你可以在这里使用ast.literal_eval()。像这样,

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

正如您在评论中提到的,您正在自己创建字典,因此以痛苦的 .txt 格式存储字典不是一个好主意,Python 提供了一个名为 Pickle 来保存其中的任何对象,使用 pickle 非常简单。

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" ) )

您可以借助此模块保存任何 Python 对象、嵌套对象或简单对象,并在以后需要时访问它的值。