Python将对列表转换为字典

use*_*861 20 python dictionary list

我有一个大约50个字符串的列表,其中一个整数表示它们在文本文档中出现的频率.我已经将其格式化如下所示,并且我正在尝试创建此信息的字典,第一个单词是值,键是旁边的数字.

string = [('limited', 1), ('all', 16), ('concept', 1), ('secondly', 1)]
Run Code Online (Sandbox Code Playgroud)

我到目前为止的代码:

my_dict = {}
for pairs in string:
    for int in pairs:
       my_dict[pairs] = int
Run Code Online (Sandbox Code Playgroud)

Ale*_*ton 45

与此类似,Python的dict()功能完全是用于转换listtuples,这是你必须:

>>> string = [('limited', 1), ('all', 16), ('concept', 1), ('secondly', 1)]
>>> my_dict = dict(string)
>>> my_dict
{'all': 16, 'secondly': 1, 'concept': 1, 'limited': 1}
Run Code Online (Sandbox Code Playgroud)


ale*_*cxe 11

只需致电dict():

>>> string = [('limited', 1), ('all', 16), ('concept', 1), ('secondly', 1)]
>>> dict(string)
{'limited': 1, 'all': 16, 'concept': 1, 'secondly': 1}
Run Code Online (Sandbox Code Playgroud)