【问题标题】:How to get a dictionary from a json file in Python?如何从 Python 中的 json 文件中获取字典?
【发布时间】:2014-02-06 00:30:32
【问题描述】:

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

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

我想得到一个字典作为字符串的键并得到一个列表作为值。然后迭代它。我怎样才能完成它?

【问题讨论】:

  • 你的意思是 for trendingtopic in json_data[category]: 在你的内部循环中吗?

标签: python json dictionary


【解决方案1】:

json_data 是一个字典。在您的第一个循环中,您正在遍历字典键的列表:

for category in json_data:

category 将包含关键字符串 - General 和 Acciones politicas。

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

for trendingtopic in category:

使用以下内容,以便遍历字典元素:

for trendingtopic in json_data[category]:

【讨论】:

  • 或者,您可以像这样迭代:for key, value in json_data.iteritems(): print key; for item in value: print item
【解决方案2】:

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

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

【讨论】:

  • iteritems 是否意味着针对简单循环的操作成本更高或更低?
  • 我认为for ... in mydict:(“简单循环”)等同于for ... in mydict.iterkeys():。当您使用iteritems() 时,我猜它会快一点,因为它将键/值对作为一个单元拉动,而不必返回并查找任何值。我的动机只是让代码看起来更好一点。
  • 太好了,如果我的 json 结构不同会怎样,例如,有时值是列表,有时是其他字典等
  • 如果上面的trending 是字典而不是列表,它只会打印它的键。如果这就是你想要的,很好,但如果你需要以不同的方式处理它们,那么你需要为每个不同的代码。
猜你喜欢
  • 2020-03-26
  • 2019-06-16
  • 1970-01-01
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-19
  • 1970-01-01
相关资源
最近更新 更多