-1

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.

Tanu
  • 1,286
  • 4
  • 16
  • 35
  • `{k.decode(): v for k, v in data}` – flakes Feb 18 '23 at 06:10
  • 1
    Does this answer your question? [Convert bytes to a string](https://stackoverflow.com/questions/606191/convert-bytes-to-a-string) – buran Feb 18 '23 at 06:13
  • 1
    And [How to convert list of key-value tuples into dictionary?](https://stackoverflow.com/q/6586310/4046632) – buran Feb 18 '23 at 06:13
  • @flakes is the code changing it to a dictionary. Thank you – Tanu Feb 18 '23 at 06:15
  • 2
    I am not sure what is the problem for you - converting the byte-string to string or converting the list of key, value tuples into list, but BOTH are long answered on SO and your question is clear duplicate. You just did no research at all – buran Feb 18 '23 at 06:57
  • Of course, I mean converting the list of key, value tuples into dict. Sorry for the mistake in the comment above – buran Feb 18 '23 at 07:04

3 Answers3

0

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

0
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'}
Yash Mehta
  • 2,025
  • 3
  • 9
  • 20
0

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'}
DarkKnight
  • 19,739
  • 3
  • 6
  • 22