Python中如何获取嵌套数据结构里的mobile字段值?已实现year字段打印
Hey there! Let's break this down step by step so you can grab that mobile number easily.
First, let's recap your data structure to make sure we're on the same page:
a = {'year':2021,'contactnum': [{'mobile': '+94#######'}, {'lan': '+94#####'}]}
The contactnum key maps to a list of dictionaries. The first item in this list is the one with the mobile key you want.
方法1:直接链式访问
Since you know exactly where the mobile entry is (first item in the contactnum list), you can access it directly with chained indexing:
# Grab the mobile number in one line mobile_number = a['contactnum'][0]['mobile'] print(mobile_number) # Output: +94#######
Let's break this down:
a['contactnum']gets the list of contact dictionaries[0]picks the first dictionary in that list (since Python uses 0-based indexing)['mobile']pulls the value associated with the 'mobile' key from that dictionary
方法2:遍历列表(更鲁棒)
If you're not sure if mobile will always be the first item, or if there might be multiple mobile entries, you can loop through the contactnum list to find it:
for contact in a['contactnum']: # Check if the current dictionary has a 'mobile' key if 'mobile' in contact: print(contact['mobile']) # Output: +94#######
This way, even if the order of entries changes or new contacts are added, you'll still find any mobile numbers present.
处理不存在的情况(可选)
If you want to avoid errors if the 'mobile' key doesn't exist, use the get() method which lets you set a default value:
# Get the first contact's mobile, or return 'No mobile number found' if it doesn't exist mobile_number = a['contactnum'][0].get('mobile', 'No mobile number found') print(mobile_number)
内容的提问来源于stack exchange,提问作者pradeep ruwan

