[Tutor] Manipulating Dictionary values

Alan Gauld alan.gauld at yahoo.co.uk
Mon Dec 26 06:11:54 EST 2016

On 26/12/16 08:03, Sunil Tech wrote:
> Hi Team,
> Dictionary is like
> a = {'a': 'New', 'b': 'Two', 'l': [{'k': 'test', 'm': 'again'}, {'k':
> 'test', 'm': 'again'}]}
> I am trying to modify a value in the dictionary value at a['l']

So make life easy for yourself and get rid of the outer dictionary
and use the python prompt to experiment:

>>> L = [{'k': 'test', 'm': 'again'}, {'k': 'test', 'm': 'again'}]
>>> [{'k':d['k'],'m':'replaced'} for d in L]
[{'k': 'test', 'm': 'replaced'}, {'k': 'test', 'm': 'replaced'}]

But that's not very general, you really should have a generator
for the dictionary that has a conditional expression within to
replace the m. But that means having a generator within a
comprehension inside a dictionary access.

It's all getting a bit ugly and overly complex and our goal as
programmers is to write clear, easily maintainable code, so
this is probably a bad idea.

Better to unroll into an explicit loop and make it obvious
what you are doing.

for d in a['l']: d['m'] = 'replaced'

Isn't that clearer?

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list