python - modify dictionary using dictionary comprehensions without creating a new dict -
i have below dictionary:
d = {'lnsd-02': 'manager', 'lnsd-03': 'manager', 'lnsd-01': 'quorum', 'lnsd-04': 'manager', 'lnsd-05': 'manager'}
i trying out dictionary comprehensions on similar lines of list comprehensions.
for in d: if i[-2:] in ('02', '05'): d[i]='quorum-manager'
how apply dictionary comprehension above code , change values keys without creating new dictionary ? below
d[i] = {i: 'quorum-manager' in d if i[-2:] in ('02', '05')}
finally, need original dictionary values changed as
d = {'lnsd-02': 'quorum-manager', 'lnsd-03': 'manager', 'lnsd-01': 'quorum', 'lnsd-04': 'manager', 'lnsd-05': 'quorum-manager'}
use dict.update
method:
d.update({i: 'quorum-manager' in d if i[-2:] in ('02', '05')})
the comprehension create new dictionary, dictionary used update contents of original dictionary d
.
given 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' in d if i[-2:] in ('02', '05')})
the result
{'lnsd-04': 'manager', 'lnsd-03': 'manager', 'lnsd-01': 'quorum', 'lnsd-05': 'quorum-manager', 'lnsd-02': 'quorum-manager'}
which matches desired result
Comments
Post a Comment