Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将此列表转换为字典_Python_List_Dictionary - Fatal编程技术网

Python 如何将此列表转换为字典

Python 如何将此列表转换为字典,python,list,dictionary,Python,List,Dictionary,我现在有一个类似这样的列表 list = [['hate', '10'], ['would', '5'], ['hello', '10'], ['pigeon', '1'], ['adore', '10']] dict = {'hate': '10', 'would': '5', 'hello': '10', 'pigeon': '1', 'adore': '10'} 我想把它转换成这样的字典 list = [['hate', '10'], ['would', '5'], ['hello

我现在有一个类似这样的列表

list =  [['hate', '10'], ['would', '5'], ['hello', '10'], ['pigeon', '1'], ['adore', '10']]
dict = {'hate': '10', 'would': '5', 'hello': '10', 'pigeon': '1', 'adore': '10'}
我想把它转换成这样的字典

list =  [['hate', '10'], ['would', '5'], ['hello', '10'], ['pigeon', '1'], ['adore', '10']]
dict = {'hate': '10', 'would': '5', 'hello': '10', 'pigeon': '1', 'adore': '10'}

因此基本上,
list[i][0]
将是键,
list[i][1]
将是值。非常感谢您的帮助:)

使用
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'}
请注意,在编辑过程中,似乎需要将值设置为整数而不是字符串(例如,
'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}
你可以做:

import numpy as np

array = np.array(list)
for i in xrange(len(list)):
    dict[array[i][0]] = array[i][1]
给出:

>>> dict
{'pigeon': '1', 'hate': '10', 'hello': '10', 'would': '5', 'adore': '10'}
输出:

{'pigeon': '1', 'hate': '10', 'hello': '10', 'would': '5', 'adore': '10'}

我想你的意思是,例如,
{'hate':'10'}
而不是
['hate':'10']
?是的,哈哈,很抱歉弄错了。另外,你想要一个字典列表还是一个字典?基本上,这样做的目的是每个键都有一个值。然后,我将在一个.txt文件中搜索这些键,该文件包含一段很长的单词。如果找到,则计数器会将键的相应值添加到总和中。最后,我必须给出总数。我不知道这是否有助于回答这个问题:(.对不起,我是个新手,非常感谢!这非常有帮助。再说一遍,这个问题我有第二部分,所以现在我有了字典,我想在一个文本文件中搜索这些键。我该如何创建一个循环来搜索这些键的文本?嗨,约翰,这真的需要一个单独的问题:搜索fir我想知道之前是否有人回答过这个问题,因为有几种Python工具可能会有所帮助。嗨,xnx,非常感谢。我已经分别问了这个问题: