将列表转换为字典在Python中

huangapple go评论61阅读模式
英文:

change list to map in python

问题

我有一个包含以下数值的列表:

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

我需要将它转换成键值对映射:

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

有没有可以用的方法。

英文:

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.

答案1

得分: 0

在Python中,字典是映射的最简单实现。

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

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

print(d)

这段代码将把你的列表转换为一个字典。

希望对你有帮助✌️

英文:

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

答案2

得分: 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'}
英文:
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'}

答案3

得分: 0

你可以在生成器的帮助下使用 dict() 函数,如下所示:

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

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

print(D)

输出:

{'abc': '123', 'xyz': '456', 'cde': '785'}
英文:

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'}

huangapple
  • 本文由 发表于 2023年2月18日 14:08:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491538.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定