简体   繁体   English

将List转换为Dictionary并使用List Comprehension将其值和键转换为整数

[英]Convert List into Dictionary and Convert its values and keys to integer with List Comprehension

suppose we have a list of list called A : 假设我们有一个名为A的列表的列表:

A = [['1', '200'], ['2', '450'], ['3', '300']]

What I want to do are convert list of lists above into a dictionary with first element as key and second as value, and after that I want to make both of keys and values converted to integer. 我想要做的是将上述列表的列表转换成字典,其中第一个元素为键,第二个为值,然后我想将键和值都转换为整数。

So it will be as follows: 因此将如下所示:

A = {1: 200, 
     2: 450,
     3: 300}

With all keys and values are integer. 与所有键和值是整数。

I tried list comprehension for this: 我为此尝试了列表理解:

A = dict(zip(int(a), int(b)) for a, b in row for row in A) 

Got error on it: 出现错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'row' is not defined

You don't need zip() here, just drop that, and you can loop directly over A and unpack into a and b : 您无需在这里使用zip() ,只需将其删除,就可以直接在A循环并解压缩为ab

A = dict((int(a), int(b)) for a, b in A)

That's a generator expression passing tuples to the dict() callable. 那是一个生成器表达式,将元组传递给可调用的dict()

If you can, you want to use a dictionary comprehension instead; 如果可以的话,您应该改用字典理解; that's available in Python 2.7 and newer (including all Python 3.x releases): 在Python 2.7和更高版本(包括所有Python 3.x版本)中可用:

A = {int(a): int(b) for a, b in A}

Demo: 演示:

>>> A = [['1', '200'], ['2', '450'], ['3', '300']]
>>> dict((int(a), int(b)) for a, b in A)
{1: 200, 2: 450, 3: 300}
>>> {int(a): int(b) for a, b in A}
{1: 200, 2: 450, 3: 300}
A = [['1', '200'],['2', '450'],['3','300']]
B_dict = {int(i[0]): int(i[1]) for i in A}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将字典转换为按其值排序的键列表? - How to convert a dictionary into a list of its keys sorted by its values? 将逗号分隔的值字符串转换为列表,并使用理解将其所有值和键转换为整数或浮点数 - Convert a comma-separated value string into a list and convert all its value and keys into integer or float using comprehension 将键列表和值列表转换为字典 - Convert list of keys and list of values to a dictionary 将字典转换为值列表,按键排序 - Convert dictionary to list of values, sorted by keys 如何在列表理解中将字典值转换为小写? - How to convert the dictionary values to lower case in list comprehension? 如何将列表列表转换为键为整数且值为 integer 所属的子列表的索引的字典? - How can I convert a list of lists to a dictionary whose keys are integers and values are the index of the sublist to which the integer belongs? 当键的值是列表列表时,如何将字典转换为 dataframe? - How to convert dictionary to dataframe when values of keys are list of list? 使用dict理解将字典列表转换为字典 - convert a list of dictionaries to a dictionary with dict comprehension 将 for 循环转换为列表理解以形成字典 - Convert for loop to list comprehension to form a dictionary 将键列表转换为嵌套字典 - convert list of keys to nested dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM