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

如何在Python字典中无需自定义类即可将两个列表以对象格式存储为键的值

实现方案

你要的效果可以通过以下几种简单方式实现,都不需要自行定义类再实例化:

1. 嵌套字典(最推荐,无额外依赖)

直接在目标键对应的值位置嵌套一层字典,用来存储带属性名的两个列表,代码如下:

# 定义两个原始列表
int_list = [1, 2, 3, 4]
str_list = ['one', 'two', 'three', 'four']

# 构造目标字典
target_dict = {
    1: {
        'integer': int_list,
        'string': str_list
    }
}

打印target_dict的输出完全符合你的要求:

{1: {'integer': [1, 2, 3, 4], 'string': ['one', 'two', 'three', 'four']}}

你可以通过target_dict[1]['integer']、target_dict[1]['string']的方式访问两个列表,也可以随时增删改嵌套层的属性。

2. SimpleNamespace(支持点号访问属性)

如果希望用对象.属性名的方式访问列表,可以用Python标准库的SimpleNamespace:

from types import SimpleNamespace

int_list = [1, 2, 3, 4]
str_list = ['one', 'two', 'three', 'four']

target_dict = {
    1: SimpleNamespace(integer=int_list, string=str_list)
}

访问方式为target_dict[1].integer、target_dict[1].string,如果需要打印时显示和字典一致的格式,用vars(target_dict[1])即可转换为字典结构。

3. namedtuple(不可变结构)

如果不需要修改存储的列表属性,可以用namedtuple实现:

from collections import namedtuple

# 先定义元组结构,无需写完整类
ListPair = namedtuple('ListPair', ['integer', 'string'])
int_list = [1, 2, 3, 4]
str_list = ['one', 'two', 'three', 'four']

target_dict = {
    1: ListPair(integer=int_list, string=str_list)
}

访问同样支持点号操作,打印时会直接显示属性名和对应列表。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:15:02