用for循环填充字典

2024-05-16 17:58:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几本大字典,除了最后几个字符外,所有的值都是一样的。在

比如:http://www:example.com/abc

现在我使用的字典是这样的:

categories = {1:'http://www:example.com/abc',
              2:'http://www:example.com/def'

再加上30K,v对。在

如何使用for循环将静态变量和结束变量相加作为值,并生成整数作为字典的键?在

static = 'http://www.example.com

end = ['abc','def']


Tags: comhttpfor字典exampledefwww静态
2条回答

使用字典理解。在

template = 'http://www.example.com/{path}'
categories = {i+1: template.format(path=e) for i, e in enumerate(end)}

由于键是一个整数范围,所以还可以使用一个列表。唯一的区别是索引从0开始,而不是从1开始。在

^{pr2}$

你可以用字典理解来做你想做的事。在

static = 'http://www.example.com/'
end = ['abc','def']

{ k:'{}{}'.format(static, v) for k,v in enumerate(end) }

但这确实引起了@mkrieger提出的问题:为什么不使用列表呢。在

相关问题 更多 >