当每个子列表包含两个元素时,如何从嵌套列表创建字典?

2024-05-17 02:34:46 发布

您现在位置:Python中文网/ 问答频道 /正文

给出一个列表,例如:

[['Dog', 'Cat'], ['Fish', 'Parrot'], ['Mouse', 'Hamster']]

如何编写函数/for循环(不使用列表理解或zip)

并返回一个字典,其中键和值是成对的:

{'Dog':'Cat', 'Fish':'Parrot', 'Mouse':'Hamster'}

Tags: 函数列表for字典zipcatparrotdog
1条回答
网友
1楼 · 发布于 2024-05-17 02:34:46

使用for循环

x = [['Dog', 'Cat'], ['Fish', 'Parrot'], ['Mouse', 'Hamster']]

y = {}
for i in x:
    y[i[0]] = i[1]

print(y)

使用dict-comprehension

print({i[0]:i[1] for i in x})

使用dict

print(dict(x))

相关问题 更多 >