Berlin
Berlin

Reputation: 1464

Add a key to existing key value pair in a dictionary

I want to add a key to existing key value pair in a dictionary, is the below code is the pythonic way to add a key to a key value pair in a dictionary ?

region = 'us-west-2'
A = {'m3.large': -1, 'm3.xlarge': -1}
B = {}
for key, value in A.items():
    B[(key,region)] = A.get((key, region), 0) + value
print(B)

output: {('m3.large', 'us-west-2'): -1, ('m3.xlarge', 'us-west-2'): -1}

Also how can I do the same thing but on the same dict and not on a new dict ?

print(A)

output: {('m3.large', 'us-west-2'): -1, ('m3.xlarge', 'us-west-2'): -1}

Thanks

Upvotes: 1

Views: 274

Answers (1)

John Kugelman
John Kugelman

Reputation: 361547

B = {}
for key, value in A.items():
    B[(key,region)] = A.get((key, region), 0) + value

This can be done in one statement with a dict comprehension.

B = {(key,region): A.get((key, region), 0) + value for key, value in A.items()}

Also how can I do the same thing but on the same dict and not on a new dict ?

dict keys are immutable, so you can't really modify them per se. You could add all the new keys and delete the old ones, but that would be inferior to just creating a new dict as you are doing now.

Upvotes: 2

Related Questions