我是Python的新手,并试图弄清楚如何使用dicts。
给出一个json数组:
{
"accounts": [
{
"alias": "mc_beeline_rub",
"fsAlias": "qb_mc_beeline",
"title": "MC",
"type": {
"id": "MC",
"title": "Счет мобильного кошелька"
},
"hasBalance": false,
"balance": null,
"currency": 643
},
{
"alias": "qw_wallet_rub",
"fsAlias": "qb_wallet",
"title": "WALLET",
"type": {
"id": "WALLET",
"title": "Visa QIWI Wallet"
},
"hasBalance": true,
"balance": {
"amount": 8.74,
"currency": 643
},
"currency": 643
},
{
"alias": "qw_wallet_usd",
"fsAlias": "qb_wallet",
"title": "WALLET",
"type": {
"id": "WALLET",
"title": "Visa QIWI Wallet"
},
"hasBalance": true,
"balance": {
"amount": 0,
"currency": 840
},
"currency": 840
},
{
"alias": "qw_wallet_eur",
"fsAlias": "qb_wallet",
"title": "WALLET",
"type": {
"id": "WALLET",
"title": "Visa QIWI Wallet"
},
"hasBalance": true,
"balance": {
"amount": 0.01,
"currency": 978
},
"currency": 978
}
]
}
我需要从“别名”:“qw_wallet_rub”的部分中提取值['balance'] ['amount'] 我对其余的数据不感兴趣,只需知道“数量”值是什么
我不知道如何选择一个特定的子字典来使用。搜索没有为我的案例提供任何有价值的结果。
希望你们能帮我解决这个问题。 感谢
答案 0 :(得分:1)
# -*- coding: utf-8 -*-
import json
a = """your json string/file"""
b = json.loads(a)
for e in b["accounts"]:
if e["alias"] == "qw_wallet_rub":
print e["balance"]["amount"]
答案 1 :(得分:0)
不能保证只有其中一个,但你可以简单地使用列表理解:
>>> data = json.loads(your_json_string)
>>> print([d["balance"]["amount"] for d in data["accounts"]
if d["alias"] == "qw_wallet_rub"])
[8.74]