Search code examples
pythonlistdictionarysublist

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'


Solution

  • Simply:

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

    I love python's simplicity

    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}:

    >>> 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