python – 字典的子列表

所以我有:

a = [["Hello", "Bye"], ["Morning", "Night"], ["Cat", "Dog"]]

我想把它转换成字典.

我试过用:

i = iter(a)  
b = dict(zip(a[0::2], a[1::2]))

但它给了我一个错误:TypeError:unhashable type:’list’

最佳答案 只是:

>>> a = [["Hello", "Bye"], ["Morning", "Night"], ["Cat", "Dog"]]
>>> dict(a)
{'Cat': 'Dog', 'Hello': 'Bye', 'Morning': 'Night'}

我喜欢python的简单性

您可以看到构建字典的所有方法的here

To illustrate, the following examples all return a dictionary equal to {"one": 1, "two": 2, "three": 3}:

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)]) #<-Your case(Key/value pairs)
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
点赞