以字典格式显示文本文件数据

时间:2013-02-22 12:50:41

标签: python dictionary

我有一个文本文件(new.txt),其中包含以下数据:

{
    "String1": {
        "Value1": {"One":"a","Two":"b","Three":"c"},
        "Value2": {"One":"aa","Two":"bb","Three":"cc"},
         }

     "String2": {
         "Value1": {"One":"a1","Two":"b1","Three":"c1"},
         "Value2": {"One":"aa1","Two":"bb1","Three":"cc1"},
         }
}

我想显示以下值: String1,value1即{“One”:“a”,“Two”:“b”,“Three”:“c”} String2,value2和一个“aa1”

我该如何显示它..

2 个答案:

答案 0 :(得分:3)

import ast
with open('new.txt') as f:
    d = ast.literal_eval(f.read())
print d['String2']['Value2']['One']

答案 1 :(得分:1)

它看起来像json,但缺少一些重要部分。与下面相比,缺少一些“,”。是复制粘贴new.txt还是一些手动格式错误?

{
    "String2": {
        "Value2": {
            "Three": "cc1", 
            "Two": "bb1", 
            "One": "aa1"
        }, 
        "Value1": {
            "Three": "c1", 
            "Two": "b1", 
            "One": "a1"
        }
    }, 
    "String1": {
        "Value2": {
            "Three": "cc", 
            "Two": "bb", 
            "One": "aa"
        }, 
        "Value1": {
            "Three": "c", 
            "Two": "b", 
            "One": "a"
        }
    }
}

如果它应该是json,使用python很容易处理:

import json
with open('new.txt') as f:
    myjson = json.loads(f.read())
print myjson['String2']['Value2']['One']
尽管如此,在eumiro的回答中看起来非常漂亮。