将列表转换为字典在Python中

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

change list to map in python

问题

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

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

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

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

有没有可以用的方法。

英文:

I have a list with the following value

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

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

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

Is there a method that I can use.

答案1

得分: 0

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

  1. L = [(b'abc', '123'), (b'xyz', '456'), (b'cde', '785')]
  2. d = {}
  3. for i in L:
  4. d[i[0]] = i[1]
  5. print(d)

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

希望对你有帮助✌️

英文:

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

  1. L=[(b'abc', '123'), (b'xyz', '456'), (b'cde', '785')]
  2. d={}
  3. for i in L:
  4. d[i[0]]=i[1]
  5. print(d)

This code will turn your list into a dictionary

Hope it helps✌️

答案2

得分: 0

  1. my_list = [(b'abc', '123'), (b'xyz', '456'), (b'cde', '785')]
  2. dic = {}
  3. for key, value in my_list:
  4. dic[key.decode()] = value
  5. print(dic) # {'abc': '123', 'xyz': '456', 'cde': '785'}
英文:
  1. my_list = [(b'abc', '123'), (b'xyz', '456'), (b'cde', '785')]
  2. dic={}
  3. for key,value in my_list:
  4. dic[key.decode()]=value
  5. print(dic) #{'abc': '123', 'xyz': '456', 'cde': '785'}

答案3

得分: 0

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

  1. L = [(b'abc', '123'), (b'xyz', '456'), (b'cde', '785')]
  2. D = dict((x.decode(), y) for x, y in L)
  3. print(D)

输出:

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

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

  1. L = [(b'abc', '123'), (b'xyz', '456'), (b'cde', '785')]
  2. D = dict((x.decode(), y) for x, y in L)
  3. print(D)

Output:

  1. {'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:

确定