Shilo
Shilo

Reputation: 313

populate dictionary with for loop

I have several large dictionaries where all the values are the same except for the last several characters.

like : http://www:example.com/abc

Right now im using a dictionary like so:

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

with an additional 30 k,v pairs.

How can I use a for loop to add the static and end variables together as the value, and generate integer as keys of a dictionary?

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

end = ['abc','def']

Upvotes: 0

Views: 172

Answers (2)

Matt Seymour
Matt Seymour

Reputation: 9395

You can do what you are trying to do with a dictionary comprehension.

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

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

But it does beg the question as raised by @mkrieger why not just use a list.

Upvotes: 2

mkrieger1
mkrieger1

Reputation: 23148

Use a dictionary comprehension.

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

Since the keys are a range of integers, you could as well use a list. The only difference is that the indices start at 0 instead of 1.

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

Upvotes: 1

Related Questions