简体   繁体   English

子列表到字典

[英]sublist to dictionary

So I have:所以我有:

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

And I want to convert it to a dictionary.我想把它转换成字典。

I tried using:我尝试使用:

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

But it gave me an error: TypeError: unhashable type: 'list'但它给了我一个错误: TypeError: unhashable type: 'list'

Simply: 只是:

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

I love python's simplicity 我喜欢python的简单性

You can see here for all the ways to construct a dictionary: 您可以在此处查看构建字典的所有方法:

To illustrate, the following examples all return a dictionary equal to {"one": 1, "two": 2, "three": 3} : 为了说明,以下示例都返回等于{"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

Maybe you can try this following code:也许你可以试试下面的代码:

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

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

And if you want your value have more than 1 value (in the form of a list), you can slightly change the code:如果你希望你的值有超过 1 个值(以列表的形式),你可以稍微更改代码:

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

to code:编码:

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

Hope it will help you:)希望它能帮助你:)

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

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