我可以帮您将 Python 中的 nametuple 转换为字典:
我有以下代码:
我有以下代码:
CommentInfo(stt=1, gid=12, uid=222)
现在我想要:
{"stt":1,"gid":12,"uid":222}
请帮助我!非常感谢!
CommentInfo(stt=1, gid=12, uid=222)
现在我想要:
{"stt":1,"gid":12,"uid":222}
请帮助我!非常感谢!
_asdict()
函数将命名元组转换为字典。>>> CommentInfo = namedtuple('CommentInfo', ["stt", "gid", "uid"])
>>> x = CommentInfo(stt=1,gid=12,uid=222)
>>> x._asdict()
OrderedDict([('stt', 1), ('gid', 12), ('uid', 222)])
namedtuples有一个._asdict()
方法,可以将其转换为OrderedDict,因此如果您拥有变量中的实例comment
,则可以使用comment._asdict()