代码之家  ›  专栏  ›  技术社区  ›  user2240542

词典的子列表

  •  3
  • user2240542  · 技术社区  · 12 年前

    所以我有:

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

    我想把它转换成一本字典。

    我尝试使用:

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

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

    2 回复  |  直到 12 年前
        1
  •  8
  •   jamylak    12 年前

    简单地说:

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

    我喜欢蟒蛇的简单

    你可以看到 here 对于构建字典的所有方法:

    为了举例说明,以下示例都返回一个等于 {"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
    
        2
  •  1
  •   hafshahfitri    2 年前

    也许您可以尝试以下代码:

    a = [
        ["Hello", "Bye"],
        ["Morning", "Night"],
        ["Cat", "Dog"]
        ]
    
    b = {}
    for x in a:
        b[x[0]] = x[1]
    print(b)
    

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

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

    要编码:

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

    希望它能帮助你:)