Python将对列表转换为字典 [英] Python convert pairs list to dictionary
本文介绍了Python将对列表转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个大约50个字符串的列表,其中一个整数表示它们在文本文档中出现的频率.我已经格式化了它,如下所示,并且正在尝试创建此信息的字典,第一个单词是值,键是旁边的数字.
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.
string = [('limited', 1), ('all', 16), ('concept', 1), ('secondly', 1)]
我到目前为止的代码:
my_dict = {}
for pairs in string:
for int in pairs:
my_dict[pairs] = int
推荐答案
Python的 dict()
函数是为转换tuple
s的list
而设计的,它就是您所拥有的:
Like this, Python's dict()
function is perfectly designed for converting a list
of tuple
s, which is what you have:
>>> string = [('limited', 1), ('all', 16), ('concept', 1), ('secondly', 1)]
>>> my_dict = dict(string)
>>> my_dict
{'all': 16, 'secondly': 1, 'concept': 1, 'limited': 1}
这篇关于Python将对列表转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文