Julionf
Julionf

Reputation: 31

Converting a 2D list to a dict

I want to convert a 2D list in a dictionary where the first element is the key and the second is the value of that key.

For example:

list = [[1,a],[2,b],[3,c]]

Turning into this dict:

dict = {1:'a', 2:'b', 3:'c'}

I could achieve that using zip to separate the 2D list in two 1D lists and zip them into a dict, but the order of keys were wrong and I think there is an easier way to do that.

Could you help me?

Upvotes: 1

Views: 1233

Answers (3)

Juan C
Juan C

Reputation: 6132

Very easy:

l = [[1,'a'],[2,'b'],[3,'c']]
d = {i[0]:i[1] for i in l}

Output:

Out[171]: {1: 'a', 2: 'b', 3: 'c'}

Edit:

Even easier :

d = dict(l)

Upvotes: 4

Sheri
Sheri

Reputation: 1413

More easier way:

l = [[1,'a'],[2,'b'],[3,'c']]
d = dict(l)
print(d)

Output:

{1: 'a', 2: 'b', 3: 'c'}

Upvotes: 1

kjmerf
kjmerf

Reputation: 4335

Something like:

lst = [[1, 'a'], [2, 'b'], [3, 'c']]

dct = {}

for x in lst:
    dct[x[0]] = x[1]

print(dct)

# {1: 'a', 2: 'b', 3: 'c'}

Upvotes: 0

Related Questions