在Python中从JSON获取多个键 [英] Get multiple keys from json in Python
问题描述
我在文件中具有以下json结构:
I have the following json structure in a file:
[
{ "Date": "timevalue", "Org": "b4256282", "Referer": "somevalue" },
{ "Date": "timevalue", "Org": "b4257482", "Referer": "somevalue" },
{ "Date": "timevalue", "Org": "b4253345", "Referer": "somevalue" },
....
]
我想提取所有的组织.
我的代码是:
import json
jdata = json.loads(str_of_above_json)
for orgs in jdata['Org']:
print(orgs)
但是此代码不起作用...我收到以下错误消息
However this code does not work ... I get the following error messag
TypeError:列表索引必须是整数,而不是str
TypeError: list indices must be integers, not str
任何人都可以让我知道我在做什么错吗?
Can anyone let me know what I am doing wrong?
推荐答案
您需要遍历列表中的每个词典,然后依次使用dict索引对dict进行索引.对于列表中的每本词典,
You need to iterate over each dictionary in the list and then index dict in turn with dict indexing. For each dictionary in the list,
- 获取第i个 词典
- 在第i 词典中获取与
Org
关联的值 - 从(2)打印该值
- get the ith dictionary
- get the value associated with
Org
in the ith dictionary - print said value from (2)
在代码中,这是
for dict_ in jdata:
org = dict_['Org']
print(org)
但是,我们拥有列表理解的能力,因此上面的代码可以更简洁地表示为
However, we have the power of list comprehension at our disposal, so the code above can more succinctly be represented by,
jdata = json.loads(str_of_above_json)
orgs = [x['Org'] for x in jdata]
print(orgs)
您当前的代码为什么不起作用?
您执行jdata['Org']
,但是[...]
是dict索引操作,并且由于jdata
是 list ,这将引发错误.
Why isn't your current code working?
You do jdata['Org']
, but [...]
is a dict indexing operation, and this will throw errors because jdata
is a list.
这篇关于在Python中从JSON获取多个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!