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

2024-09-29 17:18:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了实现我的需要的代码:

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文件:

^{pr2}$

不过,我要把这个打印出来:

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

我想得到一个字典,把键串起来,得到一个列表作为值。然后迭代它。我怎样才能做到呢?在


Tags: 代码inimportjsonfordataaswith
2条回答

json_data是一个字典。在第一个循环中,迭代字典的键列表:

for category in json_data:

类别将包含密钥字符串-通用和Acciones politica。在

您需要替换此循环,该循环迭代键的字母:

^{pr2}$

,以便在字典元素上迭代:

for trendingtopic in json_data[category]:

我将使用字典的.iteritems()方法,该方法返回键/值对:

for category, trending in json_data.iteritems():
    print category
    for topic in trending:
        print topic

相关问题 更多 >

    热门问题