[英]Accessing list within a dictionary via Python from a JSON file
我是 Python 的新手,需要一些幫助。 我正在嘗試使用 Python 從我的 JSON 文件中讀取並獲取字典中列表的值。
一旦我將 JSON 讀入我的程序,我就會:
request body = {
"providerName": "ProviderNameXYZ",
"rateRequestPayments": [
{
"amount": 128.0,
"creditorProfileId": "7539903942457444658",
"debtorProfileId": "2072612712266192555",
"paymentMethodId": "2646780961603748694016",
"currency": "EUR",
"userReference": "INVALID user ref automation single",
"reconciliationId": "343546578753349"
},
{
"amount": 129.0,
"creditorProfileId": "7539903942457444658",
"debtorProfileId": "2072612712266192555",
"paymentMethodId": "2646780961603748694016",
"currency": "EUR",
"userReference": "INVALID user ref automation single",
"reconciliationId": "343546578753340"
}
]
}
rateRequestPayments[0].amount
rateRequestPayments()[0].amount
for k, v in request_body.rateRequestPayments(): print(k, v)
for each in request_body.rateRequestPayments: print(each('amount'))
values = eval(request_body['rateRequestPayments']) print(values[0])
所有這些都以錯誤告終。 根據下面的第二條評論: request_body['rateRequestPayments'][0]['amount']
這行得通!request_body['rateRequestPayments'][0]['amount']
不適用於此。 不知道如何引用這個。我知道我遺漏了一些簡單的東西,但我不確定它是什么。 任何幫助將不勝感激。
Python 非常適合數據科學,並且具有許多適合該工作的功能。 這些功能之一是在數據集中查找數據。 body['rateRequestPayments'][<!WHICH DATA SET YOU WANT TO ACCESS>][<!VALUE YOU WANT TO FIND>]
首先,您需要在requests
和body
之間添加一個下划線,這樣它的requests_body = {...}
。
要訪問鍵值對:
requests_body["rateRequestPayments"] #to access the list of two dicts
requests_body["rateRequestPayments"][0] #to access the individual dicts by index
requests_body["rateRequestPayments"][0]["amount"] #to access the value of a particular key (in this case "amount" is the key)
要刪除鍵值對,只需使用del
語句:
del requests_body["rateRequestPayments"][0]["amount"]
這將刪除變量requests_body
中的鍵值對,因此再次嘗試訪問該鍵將引發KeyError
錯誤。
要訪問和刪除鍵值對,請使用.pop()
:
value = requests_body["rateRequestPayments"][0].pop("amount")
#value is now 128.0 and the key-value pair is deleted
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.