如何将此列表转换为字典

Joh*_*gus 4 python dictionary list

我目前的列表看起来像这样

list =  [['hate', '10'], ['would', '5'], ['hello', '10'], ['pigeon', '1'], ['adore', '10']]
Run Code Online (Sandbox Code Playgroud)

我想把它转换成这样的字典

dict = {'hate': '10', 'would': '5', 'hello': '10', 'pigeon': '1', 'adore': '10'}
Run Code Online (Sandbox Code Playgroud)

因此,基本上list [i][0]将是关键,list [i][1]将是价值观.任何帮助将非常感激 :)

xnx*_*xnx 9

使用dict构造函数:

In [1]: lst =  [['hate', '10'], ['would', '5'], ['hello', '10'], ['pigeon', '1'], ['adore', '10']]

In [2]: dict(lst)
Out[2]: {'adore': '10', 'hate': '10', 'hello': '10', 'pigeon': '1', 'would': '5'}
Run Code Online (Sandbox Code Playgroud)

请注意,从您的编辑中,您似乎需要将值设置为整数而不是字符串(例如'10'),在这种情况下,您可以将每个内部列表的第二项转换为int之前将它们传递给dict:

In [3]: dict([(e[0], int(e[1])) for e in lst])
Out[3]: {'adore': 10, 'hate': 10, 'hello': 10, 'pigeon': 1, 'would': 5}
Run Code Online (Sandbox Code Playgroud)