2015-05-05 105 views
0

我有幾個大字典,其中除最後幾個字符外,所有值都相同。使用for循環填充字典

像:

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

與另外的30 K,V對:http://www:example.com/abc

使用字典像這樣眼下即時通訊。

如何使用for循環將靜態和結束變量作爲值添加到一起,並生成整數作爲字典的鍵?

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

end = ['abc','def']

+2

如果你想要整數作爲鍵,爲什麼不簡單地使用列表? – mkrieger1

+0

@ mkrieger1說實話,我甚至都沒有想過。我希望在花20分鐘時間思考這件事之前 – Shilo

回答

2

你可以做你正在嘗試藉助字典理解的事情。

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

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

但它確實乞求由@mkrieger提出的問題爲什麼不只是使用一個列表。

1

使用字典理解。

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

由於鍵是一個整數範圍,所以也可以使用列表。唯一的區別是索引從0開始而不是1.

categories_list = [template.format(path=e) for e in end]