Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 636
user2240542 Avatar asked Sep 01 '26 08:09

user2240542


1 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
like image 126
TerryA Avatar answered Sep 03 '26 23:09

TerryA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!