如何从嵌套dict中提取caCustomerID与cust_id字段值?
从嵌套字典中提取指定键的值
给定如下Python嵌套字典my_dict(由接口JSON响应转换而来,类型为dict):
my_dict = {'SalesStatusResult': {'next_offset': -1, 'customers': [{'caCustomerID': 'N872-1665582527-adhoc-0:0', 'identifier': 'N872', 'customertype': '', 'blocked': False, 'location': 'London', 'expected_transaction_time': {'epoch': 1665582527, 'tz': 'EDT', 'dow': 'Wednesday', 'time': '09:48', 'date': '10/12/2022', 'localtime': 1665568127}, 'estimated_order_time': {'epoch': 1665582527, 'tz': 'EDT', 'dow': 'Wednesday', 'time': '09:48', 'date': '10/12/2022', 'localtime': 1665568127}, 'actual_order_time': {'epoch': 1665582527, 'tz': 'EDT', 'dow': 'Wednesday', 'time': '09:48', 'date': '10/12/2022', 'localtime': 1665568127}, 'expected_settlement_time': {'epoch': 0, 'tz': '', 'dow': '', 'time': '', 'date': '', 'localtime': 0}, 'status': 'Completed', 'status_code': 1, 'progress_percent': 100, 'state_code': 2, 'cust_id' : 'AD-17-C18' }]}}
需求是提取caCustomerID和cust_id对应的取值。
解决方案
由于customers是列表类型(即使仅包含一个元素),需要先通过索引获取列表中的字典元素,再通过键名直接取值:
# 获取caCustomerID的值 ca_customer_id = my_dict['SalesStatusResult']['customers'][0]['caCustomerID'] print(ca_customer_id) # 输出: N872-1665582527-adhoc-0:0 # 获取cust_id的值 cust_id = my_dict['SalesStatusResult']['customers'][0]['cust_id'] print(cust_id) # 输出: AD-17-C18
如果customers列表可能包含多个客户数据,可通过遍历列表批量提取:
for customer in my_dict['SalesStatusResult']['customers']: print("caCustomerID:", customer['caCustomerID']) print("cust_id:", customer['cust_id'])
内容的提问来源于stack exchange,提问作者zeroes_ones
相关产品推荐
相关产品推荐

