在json文件中的数据是在列表类型我想导入它作为字典或想转换成字典嵌套列表我怎么能这样做呢?[已关闭]

k3fezbri  于 2023-10-21  发布在  其他
关注(0)|答案(1)|浏览(116)

已关闭,此问题需要details or clarity。它目前不接受回答。
**想改善这个问题吗?**通过editing this post添加详细信息并澄清问题。

9天前关闭
Improve this question
我想在python中导入json列表数据作为字典,或者只是将嵌套的列表数据转换为python字典,我尝试了load函数,但它将数据导入为列表,帮助我解决这个问题
我试过加载和加载函数,但它不工作数据看起来像这样

[
    {
        "month": "Jan",
        "sales": "50000"
    },
    {
        "month": "Feb",
        "sales": "58000"
    },
    {
        "month": "Jan",
        "sales": "53000"
    },
    {
        "month": "Jan",
        "sales": "30000"
    },
    {
        "month": "Jan",
        "sales": "10000"
    },
    {
        "month": "Jan",
        "sales": "60000"
    },
    {
        "month": "Jan",
        "sales": "38000"
    },
    {
        "month": "Jan",
        "sales": "35000"
    },
    {
        "month": "Jan",
        "sales": "76000"
    },
    {
        "month": "Jan",
        "sales": "30200"
    },
    {
        "month": "Jan",
        "sales": "96000"
    },
    {
        "month": "Jan",
        "sales": "19000"
    }
]
fd3cxomn

fd3cxomn1#

下面的Python代码导入了你作为字典提供的JSON列表数据:

# Load the JSON data into a Python list.
json_data = json.loads('[{"month": "Jan", "sales": "50000"}, {"month": "Feb", "sales": "58000"}, {"month": "Jan", "sales": "53000"}, {"month": "Jan", "sales": "30000"}, {"month": "Jan", "sales": "10000"}, {"month": "Jan", "sales": "60000"}, {"month": "Jan", "sales": "38000"}, {"month": "Jan", "sales": "35000"}, {"month": "Jan", "sales": "76000"}, {"month": "Jan", "sales": "30200"}, {"month": "Jan", "sales": "96000"}, {"month": "Jan", "sales": "19000"}]')

# Convert the Python list to a dictionary.
sales_data = dict((sale["month"], sale["sales"]) for sale in json_data)

# Print the dictionary.
print(sales_data)

您还可以使用列表解析将嵌套列表数据转换为字典。例如,以下代码将嵌套列表数据转换为字典,其中键为月份,值为该月份的销售额列表:

sales_data = {
    month: [sale["sales"] for sale in json_data if sale["month"] == month]
    for month in set(sale["month"] for sale in json_data)
}

# Print the dictionary.
print(sales_data)

输出量:

First block
{'Jan': '19000', 'Feb': '58000'}
Second Block
{'Feb': ['58000'], 'Jan': ['50000', '53000', '30000', '10000', '60000', '38000', '35000', '76000', '30200', '96000', '19000']}

相关问题