cool77 cool77 - 2 years ago 96
Python Question

modify dictionary using dictionary comprehensions without creating a new dict

I have the below dictionary:

d = {'lnsd-02': 'manager', 'lnsd-03': 'manager', 'lnsd-01': 'quorum', 'lnsd-04': 'manager', 'lnsd-05': 'manager'}

I am trying out dictionary comprehensions on similar lines of list comprehensions.

for i in d:
if i[-2:] in ('02', '05'):

How do i apply dictionary comprehension to the above code and change values for certain keys without creating a new dictionary ?
something like below

d[i] = {i: 'quorum-manager' for i in d if i[-2:] in ('02', '05')}

finally, i need the original dictionary with values changed as

d = {'lnsd-02': 'quorum-manager', 'lnsd-03': 'manager', 'lnsd-01': 'quorum', 'lnsd-04': 'manager', 'lnsd-05': 'quorum-manager'}

Answer Source

Use the dict.update method:

d.update({i: 'quorum-manager' for i in d if i[-2:] in ('02', '05')})

The comprehension will create a new dictionary, but this dictionary will only be used to update the contents of your original dictionary d.

Given your original data:

>>> d = {'lnsd-02': 'manager', 'lnsd-03': 'manager', 
    'lnsd-01': 'quorum', 'lnsd-04': 'manager', 'lnsd-05': 'manager'}

And applying

>>> d.update({i: 'quorum-manager' for i in d if i[-2:] in ('02', '05')})

The result is

{'lnsd-04': 'manager', 'lnsd-03': 'manager', 'lnsd-01': 'quorum', 
'lnsd-05': 'quorum-manager', 'lnsd-02': 'quorum-manager'}

Which matches your desired result

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download