繁体   English   中英

子列表到字典

[英]sublist to dictionary

所以我有:

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的简单性

您可以在此处查看构建字典的所有方法:

为了说明,以下示例都返回等于{"one": 1, "two": 2, "three": 3}的字典{"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

也许你可以试试下面的代码:

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

b = {}
for x in a:
    b[x[0]] = x[1]
print(b)

如果你希望你的值有超过 1 个值(以列表的形式),你可以稍微更改代码:

b[x[0]] = x[1]

编码:

b[x[0]] = x[1:]

希望它能帮助你:)

暂无
暂无

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

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