python 嵌套 lists/dictionaries 和弹出值
python nested lists/dictionaries and popping values
对于这样一个新手问题,提前表示歉意。我刚开始写 python,我一直对从嵌套 dictionaries/lists 中弹出值感到困惑,所以我很感激任何帮助!
我有这个样本json数据:
{ "scans": [
{ "status": "completed", "starttime": "20150803T000000", "id":533},
{ "status": "completed", "starttime": "20150803T000000", "id":539}
] }
我想从 "scans" 键中弹出 'id'。
def listscans():
response = requests.get(scansurl + "scans", headers=headers, verify=False)
json_data = json.loads(response.text)
print json.dumps(json_data['scans']['id'], indent=2)
似乎不起作用,因为嵌套的 key/values 在列表中。即
>>> print json.dumps(json_data['scans']['id'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
任何人都可以指出正确的方向来让它工作吗?我的长期目标是创建一个 for 循环,将所有 id 放入另一个字典或列表中,我可以将其用于另一个功能。
json_data['scans']
returns 一个字典列表,您正在尝试使用 str 索引列表,即 []["id"]
由于显而易见的原因而失败,因此您需要使用索引来获取每个子元素:
print json_data['scans'][0]['id'] # -> first dict
print json_data['scans'][1]['id'] # -> second dict
或者查看所有 id 迭代使用 json_data["scans"]
:
返回的字典列表
for dct in json_data["scans"]:
print(dct["id"])
要保存附加到列表:
all_ids = []
for dct in json_data["scans"]:
all_ids.append(dct["id"])
或使用列表组合:
all_ids = [dct["id"] for dct in json_data["scans"]]
如果键 id
可能不在每个字典中,请在访问前使用 in
检查:
all_ids = [dct["id"] for dct in json_data["scans"] if "id" in dct]
这里如何遍历项目并提取所有 ID:
json_data = ...
ids = []
for scan in json_data['scans']:
id = scan.pop('id')
# you can use get instead of pop
# then your initial data would not be changed,
# but you'll still have the ids
# id = scan.get('id')
ids.append();
这种方法也行得通:
ids = [item.pop('id') for item in json_data['scans']]
对于这样一个新手问题,提前表示歉意。我刚开始写 python,我一直对从嵌套 dictionaries/lists 中弹出值感到困惑,所以我很感激任何帮助!
我有这个样本json数据:
{ "scans": [
{ "status": "completed", "starttime": "20150803T000000", "id":533},
{ "status": "completed", "starttime": "20150803T000000", "id":539}
] }
我想从 "scans" 键中弹出 'id'。
def listscans():
response = requests.get(scansurl + "scans", headers=headers, verify=False)
json_data = json.loads(response.text)
print json.dumps(json_data['scans']['id'], indent=2)
似乎不起作用,因为嵌套的 key/values 在列表中。即
>>> print json.dumps(json_data['scans']['id'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
任何人都可以指出正确的方向来让它工作吗?我的长期目标是创建一个 for 循环,将所有 id 放入另一个字典或列表中,我可以将其用于另一个功能。
json_data['scans']
returns 一个字典列表,您正在尝试使用 str 索引列表,即 []["id"]
由于显而易见的原因而失败,因此您需要使用索引来获取每个子元素:
print json_data['scans'][0]['id'] # -> first dict
print json_data['scans'][1]['id'] # -> second dict
或者查看所有 id 迭代使用 json_data["scans"]
:
for dct in json_data["scans"]:
print(dct["id"])
要保存附加到列表:
all_ids = []
for dct in json_data["scans"]:
all_ids.append(dct["id"])
或使用列表组合:
all_ids = [dct["id"] for dct in json_data["scans"]]
如果键 id
可能不在每个字典中,请在访问前使用 in
检查:
all_ids = [dct["id"] for dct in json_data["scans"] if "id" in dct]
这里如何遍历项目并提取所有 ID:
json_data = ...
ids = []
for scan in json_data['scans']:
id = scan.pop('id')
# you can use get instead of pop
# then your initial data would not be changed,
# but you'll still have the ids
# id = scan.get('id')
ids.append();
这种方法也行得通:
ids = [item.pop('id') for item in json_data['scans']]