Thank you Steven D'Aprano and Alan Gauld. On Mon, Dec 26, 2016 at 4:41 PM, Alan Gauld via Tutor <tutor@python.org> wrote:
> 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 > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor