简体   繁体   English

将列表列表转换为 python 中的唯一字典

[英]Convert list of lists to unique dictionary in python

I have the following list of lists: [[100, 23], [101, 34], [102, 35]... ]我有以下列表: [[100, 23], [101, 34], [102, 35]... ]

How can i convert it to a dictionary like that: {100: 23, 101: 34, 102: 35... }我怎样才能将它转换成这样的字典: {100: 23, 101: 34, 102: 35... }

Here is what i tried:这是我尝试过的:

myDict = dict(map(reversed, myList))

This code works, but it will give the opposite of what i want in the dictionary: {23: 100, 101:34..}此代码有效,但它将与我在字典中想要的相反: {23: 100, 101:34..}

You can pass a list with this format to dict() and it will convert it for you.您可以将具有这种格式的列表传递给dict() ,它会为您转换它。

myList = [[100, 23], [101, 34], [102, 35]]

myDict = dict(myList)

print(myDict)

According to docs page for dict()根据dict()的文档页面

. . . . . . the positional argument must be an iterable object.位置参数必须是可迭代的 object。 Each item in the iterable must itself be an iterable with exactly two objects.可迭代对象中的每个项目本身必须是恰好具有两个对象的可迭代对象。 The first object of each item becomes a key in the new dictionary, and the second object the corresponding value.每一项的第一个 object 成为新字典中的一个键,第二个 object 成为对应的值。

and here is an example for the same doc page:这是同一文档页面的示例:

...
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])

returns a dictionary equal to {"one": 1, "two": 2, "three": 3}返回一个等于{"one": 1, "two": 2, "three": 3}的字典

L = []
A = {}
for x,y in L:
    A[x] = y

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM