【问题标题】:how can i make a json file to a dictionary?如何将 json 文件制作成字典?
【发布时间】:2015-04-23 20:59:21
【问题描述】:

我是 python 的初学者。我的 json 文件是:

{
    "dog": {
        "dog1": ["cat1", "cat2"],
        "dog2": ["cat2", "cat1"]
    },
    "cat": {
        "cat1": ["dog1", "dog2"],
        "cat2": ["dog1", "dog2"]
    }
}

我将 json 文件保存到变量 x 中:

import json

f = open(jsonfile, 'r')
x = json.load(f)
f.close()

现在我想制作两本名为“cat”和“dog”的字典。我该怎么做? P.s 每次有人调用程序时,文件 json 都可能不同。特别是,它可以有更多或更少的狗或猫。

【问题讨论】:

    标签: python json dictionary


    【解决方案1】:
    import json
    
    with open(filename, 'r') as f:
        animals = json.load(f)
    
    dog_dict = animals['dog']
    cat_dict = animals['cat']
    

    【讨论】:

    • 如果我想制作这样的字典:dog_status = { 'dog1': 'Homeless', 'dog2' : 'Homeless' } 我该怎么办?
    • 要么你只需要更改 JSON 文件本身,并保持相同的代码,要么我不明白你的第二个问题。
    【解决方案2】:

    x 是一个包含您的 json 代码的字典,该字典已转换为 python 字典 json.load(f)。在你的 json 中有更多的字典。没有什么特别之处,只要你愿意,只需将它们分配给一个新变量即可。

    dog_dict = x['dog']
    

    【讨论】:

    • 如果我想制作这样的字典:dog_status = { 'dog1': 'Homeless', 'dog2' : 'Homeless' } 我该怎么办?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多