You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何获取嵌套数据结构里的mobile字段值?已实现year字段打印

如何获取字典列表中的mobile信息?

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:47:38