Federico Gentile
Federico Gentile

Reputation: 5940

Appending different items to different keys in Python dictionary

I have initialized a dictionary like so:

dic = {'A':[],'B':[],'C':[]}

My goal is to fill the dictionary by appending some values like so:

{'A': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 'B': [0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
 'C': [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]}

The way I was able to do it is by using the following lines of code:

for j in range(0,10):
    dic['A'].append(j)
    dic['B'].append(j*2)
    dic['C'].append(j*3)

My goal is to do such procedure in a smart and more elegant way. I would like this:

dic[['A','B','C']].append(j,j*2,j*3)

Do you have any idea on how to do it?

Note: my example could be misleading, I apologize. The reason why I append j, j*2 and j*3 is just for demonstrational purposes; the appended value could be very generic for example letters or other random numbers.

Upvotes: 0

Views: 78

Answers (2)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48120

For achieving what you want, you may create a dict comprehension expression:

keys = ['A', 'B', 'C']

my_dict = {key: [j*i for j in range(10)] for i, key in enumerate(keys, 1)}

where my_dict will hold the value:

{
    'A': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
    'B': [0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
    'C': [0, 3, 6, 9, 12, 15, 18, 21, 24, 27], 
}

Upvotes: 3

JuniorCompressor
JuniorCompressor

Reputation: 20025

The following will have the expected result:

keys = ['A', 'B', 'C']

print({
    key: range(0, 10 * i, i)
    for i, key in enumerate(keys, 1)
})

Result:

{
    'A': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
    'C': [0, 3, 6, 9, 12, 15, 18, 21, 24, 27], 
    'B': [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
}

Upvotes: 5

Related Questions