Python 将对列表转换为字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22614980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:17:10  来源:igfitidea点击:

Python convert pairs list to dictionary

pythonlistdictionary

提问by user2968861

I have a list of about 50 strings with an integer representing how frequently they occur in a text document. I have already formatted it like shown below, and am trying to create a dictionary of this information, with the first word being the value and the key is the number beside it.

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

string = [('limited', 1), ('all', 16), ('concept', 1), ('secondly', 1)]

The code I have so far:

我到目前为止的代码:

my_dict = {}
for pairs in string:
    for int in pairs:
       my_dict[pairs] = int

采纳答案by Alex Thornton

Like this, Python's dict()function is perfectly designed for converting a listof tuples, which is what you have:

像这样,Python 的dict()函数完美地设计用于转换 a listof tuples,这就是你所拥有的:

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

回答by alecxe

Just call dict():

只需致电dict()

>>> string = [('limited', 1), ('all', 16), ('concept', 1), ('secondly', 1)]
>>> dict(string)
{'limited': 1, 'all': 16, 'concept': 1, 'secondly': 1}

回答by vz0

The stringvariable is a list of pairs. It means you can do something somilar to this:

string变量是对的列表。这意味着你可以做一些类似的事情:

string = [...]
my_dict = {}
for k, v in string:
  my_dict[k] = v

回答by V?n Long

Make a pair of 2 lists and convert them to dict()

制作一对 2 列表并将它们转换为dict()

list_1 = [1,2,3,4,5]
list_2 = [6,7,8,9,10]
your_dict = dict(zip(list_1, list_2))