Newbie Variable Substitution Question

C

ckrieg

Just a quick question. Consider this:

dict01 = { '1': 'a', '2': 'b' }

for c in range(1, 3):
print "%(c)s" % locals(), "%(1)s" % dict01

Returns:

1 a
2 a

But, using this loop instead:

for c in range(1, 3):
print "%(c)s %(1)s" % (locals(), dict01)

Results in an error: TypeError: format requires a mapping

Why doesn't the second loop work? It seems to be a cleaner way of
doing this. Am I missing something?
 
S

Skip Montanaro

ckrieg> for c in range(1, 3):
ckrieg> print "%(c)s %(1)s" % (locals(), dict01)

ckrieg> Results in an error: TypeError: format requires a mapping

ckrieg> Why doesn't the second loop work? It seems to be a cleaner way
ckrieg> of doing this. Am I missing something?

The right-hand argument to the % operator is a tuple of dictionaries, not a
dictionary.

Try something like this instead:

class MultiDict(dict):
def __init__(self, *args):
self._dicts = args

def __getitem__(self, key):
for d in self._dicts:
try:
return d[key]
except KeyError:
pass
raise KeyError, key

def has_key(self, key):
for d in self._dicts:
if key in d:
return True
return False

dict01 = { '1': 'a', '2': 'b' }
for c in range(1, 3):
print "%(c)s %(1)s" % MultiDict(locals(), dict01)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top