python - 子列表到字典

标签 python list dictionary sublist

所以我有:

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

关于python - 子列表到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15875678/

相关文章:

python - 在没有正则表达式的情况下检查整个单词是否在python中的文本文件中

python - 为什么我从看似正确对齐的代码中得到 `TabError`?

c# - 获取可用(语言)resx 文件的列表

java - LinkedList 中的大负整数表示

ios - 如何在 Swift 中组合两个 Dictionary 实例?

.net - 使用 .ToDictionary 将 List(Of KeyValuePair(Of String,Int32)) 转换为 Dictionary(Of String, Int32)

python - Serializer.is_valid() 始终返回 False。 Serializer.errors 为空

python - 在 Windows 上的 Django 应用程序中使用 PIL 时遇到问题

python |获取二维列表的第一个元素

python - 如何选择某些字典键,然后将整个字典移动到单独的列表