gpt4 book ai didi

python - 在 python 中使用动态路径访问字典值

转载 作者:行者123 更新时间:2023-11-28 17:16:22 24 4
gpt4 key购买 nike

我有这段代码可以从字典对象中提取一个值

extracted_value = response_content["retrievePolicyBillingSummariesResponse"]["billingSummaries"]["policyBillingSummary"][0]["billingSummary"]["lastPayment"]["status"]
extracted_value = response_content["retrievePolicyBillingSummariesResponse"]["billingSummaries"]["policyBillingSummary"][0]["billingSummary"]["bill"]["dueDate"]

这些只是两个示例,但我有十几个具有不同键/路径组合的示例。我怎样才能使用模块调用它们并做这样的事情

def get_value_from_content (response_content, my_path):
# how can I use the value in my_path as the key instead of this hard coded path ?
extracted_value = response_content["retrievePolicyBillingSummariesResponse"]["billingSummaries"]["policyBillingSummary"][0]["billingSummary"]["lastPayment"]["status"]
#extracted_value = response_content using my_path is what I would like to do
return extracted_value

#I get this from a REST API call but skipping the code here and just hard coding to ask the question here
response_content = {u'retrievePolicyBillingSummariesResponse': {u'billingSummaries': {u'policyBillingSummary': [{u'policy': {u'status': u'A', u'policyNumber': u'xyz123', u'writingCompany': u'FBI', u'renewalFlag': u'false', u'convertedRenewalOffer': u'false', u'termExpirationDate': u'2017-06-26', u'lineOfBusiness': u'PC', u'termEffectiveDate': u'2016-06-26', u'riskState': u'CA', u'insureds': {u'namedInsuredSummary': [{u'preferredPostalAddress': {u'streetAddressLine': u'1 disney', u'cityName': u'palo alto', u'zipCode': u'94100', u'isoRegionCode': u'CA'}, u'name': {u'lastName': u'DOE', u'fullName': u'john doe', u'firstName': u'john'}}]}, u'additionalInterests': {u'additionalInterest': [{u'billTo': u'N', u'name': {u'partyType': u'Organization'}}]}, u'type': u'PA', u'statusDescription': u'Active', u'dataSource': u'from_heaven'}, u'billingSummary': {u'paymentRestriction': u'false', u'nextInstallmentAmount': u'0.00', u'bill': {u'installmentNumber': u'1', u'statementDate': u'2016-06-26', u'paymentPlan': u'Direct', u'installmentAmount': u'12.00', u'totalBillAmountDue': u'1.76', u'previousBalance': u'0.00', u'dueDate': u'2016-06-26', u'billingPlan': u'ANN'}, u'lastPayment': {u'status': u'A'}, u'currentBalance': u'16.66', u'payOffAmount': u'15.66', u'isRestrictedToPay': u'false'}}]}}}

my_path = '["retrievePolicyBillingSummariesResponse"]["billingSummaries"]["policyBillingSummary"][0]["billingSummary"]["lastPayment"]["status"]'
get_extracted_item = get_value_from_content(response_content,my_path)

my_path = '["retrievePolicyBillingSummariesResponse"]["billingSummaries"]["policyBillingSummary"][0]["billingSummary"]["bill"]["dueDate"]'
get_extracted_item = get_value_from_content(response_content,my_path)

最佳答案

首先,编写像这样的小实用函数会更容易

def extract_from_dictionary(dictionary, *keys_or_indexes):
value = dictionary
for key_or_index in keys_or_indexes:
value = value[key_or_index]
return value

正如我们从您的示例中看到的那样,有一个名为 billingSummary 的对象出现在所需的路径中,因此我们可以避免使用样板文件

def get_billing_summary(response_content):
return extract_from_dictionary(
response_content,
"retrievePolicyBillingSummariesResponse",
"billingSummaries",
"policyBillingSummary",
0,
"billingSummary")

那么我们可以简单的写

def get_value_from_content(response_content, *keys):
billing_summary = get_billing_summary(response_content)
extracted_value = extract_from_dictionary(billing_summary,
*keys)
return extracted_value

并获取所需的对象,例如

last_payment_status = get_value_from_content(response_content,
"lastPayment",
"status")
bill_due_date = get_value_from_content(response_content,
"bill",
"dueDate")
print("last_payment_status:", last_payment_status)
print("bill_due_date:", bill_due_date)

给我们

last_payment_status: A
bill_due_date: 2016-06-26

关于python - 在 python 中使用动态路径访问字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43882048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com