I have a complicated dictionary from which I need to get the account number and balance.
response = requests.request("GET", url=HOST_GET str("8af*********************e66b024e"), headers=headers, data=payload)
data = response.json()
response
{
"reportKey": "8af*********************e66b024e",
"status": "COMPLETE",
"items": [
{
"glAccount": {
"encodedKey": "8af6a********b66017*********00e",
"glCode": "1235802509PLN",
"type": "ASSET",
"usage": "DETAIL",
"name": "Some account 2",
"stripTrailingZeros": false,
"currency": {
"code": "USD"
}
},
"amounts": {
"openingBalance": 18.1200000000
}
},
{
"glAccount": {
"encodedKey": "8a**********10018************2e2",
"glCode": "12188009912PKOUSD01",
"type": "ASSET",
"usage": "DETAIL",
"name": "UAH account(payment channel acct.)",
"stripTrailingZeros": false,
"currency": {
"code": "USD"
}
},
"amounts": {
"openingBalance": 155532.5900000000
}
},
{
"glAccount": {
"encodedKey": "8af*********0719d0179***********f",
"glCode": "1134800294USD",
"type": "ASSET",
"usage": "DETAIL",
"name": "UAH account",
"stripTrailingZeros": false,
"currency": {
"code": "USD"
}
},
"amounts": {
"openingBalance": 455219.9500000000
}
},
{
"glAccount": {
"encodedKey": "8*************5fed***************1a4",
"glCode": "124567376001EUR",
"type": "ASSET",
"usage": "DETAIL",
"name": "EUR account",
"stripTrailingZeros": false,
"currency": {
"code": "EUR"
}
},
"amounts": {
"openingBalance": 14.0000000
}
}
]
}
I hard-coded the search, but the code must be redone constantly when new accounts appear.
if data["items"][2]["glAccount"]["glCode"] == "1134800294USD":
glaccount = data["items"][2]["glAccount"]["glCode"]
amount1 = data["items"][2]["amounts"]["openingBalance"]
print('Account -', data["items"][2]["glAccount"]["glCode"], "Amount -", data["items"][2]["amounts"]["openingBalance"])
response
Account - 1134800294USD Amount - 455219.95
I need to find the right account and then get the amount in the account. I have little experience in this, so please help.
CodePudding user response:
Can try below for loop to get the values, instead of print you can save them as variable or create new dictionary.
for item in json["items"]:
print(f'Account ID: {item["glAccount"]["glCode"]}')
print(f'Account Balance: {item["amounts"]["openingBalance"]}')
Example;
accounts={}
for item in json["items"]:
account_id = ({item["glAccount"]["glCode"]})
account_balance = ({item["amounts"]["openingBalance"]})
accounts_to_be_added = {f'{account_id}': account_balance}
accounts.update(accounts_to_be_added)