Yann M
Yann M

Reputation: 41

Populate a dictionary with for loop

I'd like to create a dictionary that would look like this:

{'area1': ['x1_area1', 'x2_area1'], 'area2': ['x1_area2', 'x2_area2']}

I'm trying to use a for loop:

dict_ ={}
keys =["area1","area2"]
for key in keys : 
    dict_ = {key : ["x1_"+ key,"x2_"+ key]}
    dict_.update(dict_)

But I get this output:

{'area2': ['x1_area2', 'x2_area2']}

Upvotes: 1

Views: 736

Answers (5)

goverland
goverland

Reputation: 1

When looking at how to add items to a dictionaries, it seems like dict_[key] = "answer" is the way to go.

dict_ = {}
keys = ["area1", "area2"]
for key in keys:
    dict_[key] = ["x1_" + key, "x2_" + key]
print(dict_)

https://www.w3schools.com/python/python_dictionaries.asp

Upvotes: 0

dimay
dimay

Reputation: 2804

Try it:

keys =["area1","area2"]
dict_ = {}
for key in keys : 
    dict_[key] = ["x1_"+ key,"x2_"+ key]
    
dict_

Upvotes: 4

deadshot
deadshot

Reputation: 9061

Try this

res = {k: [f'{x}_{k}' for x in ('x1', 'x2')] for k in keys}
print(res)

Output:

{'area1': ['x1_area1', 'x2_area1'], 'area2': ['x1_area2', 'x2_area2']}

Upvotes: 3

Konrad Rudolph
Konrad Rudolph

Reputation: 545558

Inside your loop, you’re redefining dict_ and thus overwriting the existing values. Use a different variable name, or just inline its usage entirely:

dict_ = {}
keys = ["area1", "area2"]
for key in keys:
    dict_.update({key : ["x1_" + key, "x2_" + key]})

This is taking over 100% of your code and just fixing the specific issues. There are better, more “Pythonic” solutions for this problem, which are explained in other answers.

Upvotes: 1

Aviv Yaniv
Aviv Yaniv

Reputation: 6298

The original code overrides the first value.

The following code will update without override:


keys =["area1","area2"]

dict_ = {}
for key in keys :
    x = {key : ["x1_"+ key,"x2_"+ key]}
    dict_.update(x)

# {'area1': ['x1_area1', 'x2_area1'], 'area2': ['x1_area2', 'x2_area2']}
print(dict_)


Upvotes: 0

Related Questions