Prev: Python, Reportlabs, Pil and Windows 7 (64bit)
Next: bypass UAC control through python script (to be run from batchfile)
From: Gnarlodious on 11 Mar 2010 11:02 I am trying to grok this documentation but need help: http://docs.python.org/library/collections.html#defaultdict-examples In a perfect world the dict looks like this: plistDict={'Style':'ExternalURL', 'Ref':'http://Gnarlodious.com/', 'Tip':'Opens in a new window', 'Text':'Gnarlodious.com'} Let's say I want to prep a dict from a plist to insert the values into an HTML link string: "<a class='%(Style)s' href='%(Ref)s' title='%(Tip)s'>%(Text)s</a>" % plistDict However, in this imperfect world the dict might look like this: plistDict={'Ref':'http://Gnarlodious.com/', 'Text':'Gnarlodious.com'} which would error: KeyError: 'Style' So using defaultdict: from collections import defaultdict How do create a dict assigning every missing key with a default string? -- Gnarlie
From: George Sakkis on 11 Mar 2010 11:20 On Mar 11, 5:02 pm, Gnarlodious <gnarlodi...(a)gmail.com> wrote: > I am trying to grok this documentation but need help:http://docs.python.org/library/collections.html#defaultdict-examples > > In a perfect world the dict looks like this: > plistDict={'Style':'ExternalURL', 'Ref':'http://Gnarlodious.com/', > 'Tip':'Opens in a new window', 'Text':'Gnarlodious.com'} > > Let's say I want to prep a dict from a plist to insert the values into > an HTML link string: > "<a class='%(Style)s' href='%(Ref)s' title='%(Tip)s'>%(Text)s</a>" % > plistDict > > However, in this imperfect world the dict might look like this: > plistDict={'Ref':'http://Gnarlodious.com/', 'Text':'Gnarlodious.com'} > > which would error: > KeyError: 'Style' > > So using defaultdict: > from collections import defaultdict > > How do create a dict assigning every missing key with a default > string? "<a class='%(Style)s' href='%(Ref)s' title='%(Tip)s'>%(Text)s</a>" % defaultdict(lambda:'_MISSING_', plistDict) HTH, George
From: Gnarlodious on 11 Mar 2010 11:27
On Mar 11, 9:20 am, George Sakkis wrote: > > How do create a dict assigning every missing key with a default > > string? > > "<a class='%(Style)s' href='%(Ref)s' title='%(Tip)s'>%(Text)s</a>" % > defaultdict(lambda:'_MISSING_', plistDict) Brilliant, I love Python. -- Gnarlie |