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

如何在不指定键名的情况下获取嵌套字典的首个外层键

获取嵌套字典的外层第一个键

针对你这种外层键不固定的情况,有几种简单实用的实现方式:

方法1:通过next()迭代字典键

字典本身是可迭代对象,迭代时默认返回键。用next()可以直接取出第一个迭代到的键:

def get_first_outer_key(nested_dict):
    first_key = next(iter(nested_dict))
    return nested_dict[first_key]

# 测试示例
dict1 = {"DICT_KEY1": {"nestKey1": "val", "nestKey2": "val", "nestKey3": "val"}}
print(get_first_outer_key(dict1))

*Python 3.7+*中字典会严格保留插入顺序,所以next()取到的就是第一个插入的键;如果是更早版本,字典是无序的,这种方式取到的是任意键,但如果你的场景中外层始终只有一个键,完全不受影响。

方法2:转列表取第一个键

把字典的键转换成列表后,直接取索引为0的元素:

def get_first_outer_key(nested_dict):
    first_key = list(nested_dict.keys())[0]
    return nested_dict[first_key]

# 测试示例
dict1 = {"DICT_KEY1": {"nestKey1": "val", "nestKey2": "val", "nestKey3": "val"}}
print(get_first_outer_key(dict1))

这种写法直观易懂,适合外层键数量极少的场景;如果字典规模很大,转列表会占用额外内存,但你的场景下完全没问题。

方法3:解构赋值快速取值

如果外层字典只有一个键值对,可以直接用解构赋值一步拿到内层字典:

def get_first_outer_key(nested_dict):
    (_, inner_dict), = nested_dict.items()
    return inner_dict

# 测试示例
dict1 = {"DICT_KEY1": {"nestKey1": "val", "nestKey2": "val", "nestKey3": "val"}}
print(get_first_outer_key(dict1))

这种写法最简洁,专门针对外层只有一个键值对的场景,同时能直接拿到内层字典,不需要单独存键名。

内容的提问来源于stack exchange,提问作者pillow

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:12:46