加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何从Python中的json文件中获取字典?

发布时间:2020-12-20 11:33:20 所属栏目:Python 来源:网络整理
导读:我得到了这个代码来实现我的需求: import jsonjson_data = []with open("trendingtopics.json") as json_file: json_data = json.load(json_file)for category in json_data: print category for trendingtopic in category: print trendingtopic 这是我的j
我得到了这个代码来实现我的需求:

import json

json_data = []
with open("trendingtopics.json") as json_file:
    json_data = json.load(json_file)

for category in json_data:
    print category
    for trendingtopic in category:
        print trendingtopic

这是我的json文件:

{
    "General": ["EPN","Pe?a Nieto","México","PresidenciaMX"],"Acciones politicas": ["Reforma Fiscal","Reforma Energética"]
}

但是我打印出来了:

Acciones politicas
A
c
c
i
o
n
e
s

p
o
l
i
t
i
c
a
s
General
G
e
n
e
r
a
l

我想得到一个字典是字符串键并得到一个列表作为值.然后迭代它.我怎么能完成它?

解决方法

json_data是一本字典.在第一个循环中,您将迭代字典键的列表:

for category in json_data:

类别将包含关键字符串 – General和Acciones politicas.

你需要替换这个遍历键字母的循环:

for trendingtopic in category:

使用下面的代码,以便迭代字典元素:

for trendingtopic in json_data[category]:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读