[英]Converting a 2D list to a dict
I want to convert a 2D list in a dictionary where the first element is the key and the second is the value of that key.我想在字典中转换一个二维列表,其中第一个元素是键,第二个是该键的值。
For example:例如:
list = [[1,a],[2,b],[3,c]]
Turning into this dict:变成这个字典:
dict = {1:'a', 2:'b', 3:'c'}
I could achieve that using zip to separate the 2D list in two 1D lists and zip them into a dict, but the order of keys were wrong and I think there is an easier way to do that.我可以使用 zip 将两个一维列表中的二维列表分开并将它们压缩到一个字典中,但是键的顺序是错误的,我认为有一种更简单的方法可以做到这一点。
Could you help me?你可以帮帮我吗?
Very easy:好简单:
l = [[1,'a'],[2,'b'],[3,'c']]
d = {i[0]:i[1] for i in l}
Output:输出:
Out[171]: {1: 'a', 2: 'b', 3: 'c'}
Edit:编辑:
Even easier :更简单:
d = dict(l)
More easier way:更简单的方法:
l = [[1,'a'],[2,'b'],[3,'c']]
d = dict(l)
print(d)
Output:输出:
{1: 'a', 2: 'b', 3: 'c'}
Something like:就像是:
lst = [[1, 'a'], [2, 'b'], [3, 'c']]
dct = {}
for x in lst:
dct[x[0]] = x[1]
print(dct)
# {1: 'a', 2: 'b', 3: 'c'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.