如何创建一个具有重复键值的字典,其中键是列表,值是值的列表。

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

How to create a dictionary with repeating key values in list and list of values

问题

D = {1: ['A', 'B', 'C'], 2: ['D', 'E'], 3: ['F']}
英文:
Key_list = [1,1,1,2,2,3]

Value_list = ['A','B','C','D','E','F']

To get something like:

D = {1:['A','B','C'],2:['D','E'],3:['F']}

答案1

得分: 5

你可以遍历zip过的键和值,根据需要设置或更新字典的值:

d = dict()
for k, v in zip(Key_list, Value_list):
    d[k] = d.get(k, []) + [v]

输出:

{
 1: ['A', 'B', 'C'],
 2: ['D', 'E'],
 3: ['F']
}
英文:

You could loop over the zipped keys and values, setting or updating the dict values as required:

d = dict()
for k, v in zip(Key_list, Value_list):
    d[k] = d.get(k, []) + [v]

Output:

{
 1: ['A', 'B', 'C'],
 2: ['D', 'E'],
 3: ['F']
}

huangapple
  • 本文由 发表于 2023年2月24日 10:43:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552175.html
匿名

发表评论

匿名网友

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

确定