从文件中读取python dict

发布于 2021-01-29 14:59:36

我有一个包含多个词典的文件,如下所示:

{'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文件。如果字典的构造不正确,我确定可以修改生成此输出的脚本。

关注者
0
被浏览
78
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    正如您在评论中提到的,您要自己创建字典,因此以痛苦的.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对象(嵌套的或简单的),并在以后需要时访问其值。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看