英文:
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 zip
ped 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']
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论