【问题标题】:How to parse dictionary value with list of lists into a pydantic class?如何将带有列表列表的字典值解析为 pydantic 类?
【发布时间】:2021-07-26 16:00:59
【问题描述】:

如何将 Python 字典解析为 pydantic 类?

示例:

{"one":[["foo","bar"],["foo1","bar1"]]}

【问题讨论】:

  • 那不是数组数组。那是一个有列表的列表。
  • 糟糕!))) 非常感谢
  • “描述一个模型”是什么意思?
  • @Mark 可能,他们的意思是将字典解析成一个 pydantic 类,所以 List[List[str]],或者在 Python 3.9 + list[list[str]]
  • 为我工作类 SuperClass(BaseModel): one: List[List[str]]

标签: python dictionary pydantic


【解决方案1】:

值的类型是List[List[str],所以就这样输入。

In [1]: from pydantic import BaseModel

In [2]: from typing import List

In [3]: class X(BaseModel):
   ...:     one: List[List[str]]
   ...: 

In [4]: raw = {"one":[["foo","bar"],["foo1","bar1"]]}

In [5]: obj = X(**raw)

In [6]: obj
Out[6]: X(one=[['foo', 'bar'], ['foo1', 'bar1']])

In [7]: obj.one
Out[7]: [['foo', 'bar'], ['foo1', 'bar1']]

【讨论】:

    猜你喜欢
    • 2023-02-09
    • 1970-01-01
    • 2021-12-09
    • 2021-11-26
    • 2018-02-11
    • 2019-08-20
    • 2021-12-30
    • 2020-02-25
    • 2014-10-07
    相关资源
    最近更新 更多