sublist to dictionary

Question:

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'

Asked By: user2240542

||

Answers:

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
Answered By: TerryA

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 :

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

to code :

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

Hope it will help you 🙂

Answered By: hafshahfitri
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.