change list to map in python

Question:

I have a list with the following value

[(b'abc', '123'), (b'xyz', '456'), (b'cde', '785')]

I need to change it to map with key value pair :

('abc','123'),('xyz','456'),('cde','785')

Is there a method that I can use.

Asked By: Tanu

||

Answers:

In python, dictionaries are the simplest implementation of a map.


L=[(b'abc', '123'), (b'xyz', '456'), (b'cde', '785')]

d={}
for i in L:
    d[i[0]]=i[1]

print(d)

This code will turn your list into a dictionary

Hope it helps✌️

Answered By: Tushar Bansal
my_list = [(b'abc', '123'), (b'xyz', '456'), (b'cde', '785')]
dic={}
for key,value in my_list:
    dic[key.decode()]=value
print(dic) #{'abc': '123', 'xyz': '456', 'cde': '785'}
Answered By: Yash Mehta

You can utilise the dict() function in conjunction with a generator as follows:

L = [(b'abc', '123'), (b'xyz', '456'), (b'cde', '785')]

D = dict((x.decode(), y) for x, y in L)

print(D)

Output:

{'abc': '123', 'xyz': '456', 'cde': '785'}
Answered By: Pingu
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.