📜  Python – 将命名元组列表转换为字典

📅  最后修改于: 2022-05-13 01:54:45.862000             🧑  作者: Mango

Python – 将命名元组列表转换为字典

在本文中,我们将使用Python将命名元组的列表转换为字典。

通过使用 dict() 方法,我们可以将命名元组列表转换为字典。在此之前,我们必须使用 _asdict() 方法将其转换为字典。

首先,我们必须使用 _asdict() 方法将 namedtuple 转换为每个元素中的字典,最后使用 dict() 方法转换为字典

句法:

for i in list:
     print(dict(i._asdict()))

在哪里,

该列表是一个命名元组

示例:将 namedtuple 转换为字典的Python程序

Python3
# import named tuple
from collections import namedtuple
 
# create a named tuple named DETAILS with three columns
DETAILS = namedtuple("DETAILS", "Name, Age, Subject")
 
# create 5 students
a = [DETAILS("ojaswi", 21, "python"),
     DETAILS("sireesha", 21, "python"),
     DETAILS("gnanesh", 23, "php"),
     DETAILS("priyank", 21, "java"),
     DETAILS("ojaswi", 22, "big-data")]
 
# convert into dictionary
# using dict method
for i in a:
    print(dict(i._asdict()))


Python3
# import named tuple
from collections import namedtuple
 
# create a named tuple named DETAILS with one column
DETAILS = namedtuple("DETAILS", "Name")
 
# create 5 students
a = [DETAILS("ojaswi"),
     DETAILS("sireesha"),
     DETAILS("gnanesh"),
     DETAILS("priyank"),
     DETAILS("ojaswi")]
 
# convert into dictionary
# using dict method
for i in a:
    print(dict(i._asdict()))


输出:

示例:将 namedtuple 转换为字典的Python程序

Python3

# import named tuple
from collections import namedtuple
 
# create a named tuple named DETAILS with one column
DETAILS = namedtuple("DETAILS", "Name")
 
# create 5 students
a = [DETAILS("ojaswi"),
     DETAILS("sireesha"),
     DETAILS("gnanesh"),
     DETAILS("priyank"),
     DETAILS("ojaswi")]
 
# convert into dictionary
# using dict method
for i in a:
    print(dict(i._asdict()))

输出: