"Murali" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> In Python, dictionaries can have any hashable value as a string. In
> particular I can say
>
> d = {}
> d[(1,2)] = "Right"
> d["(1,2)"] = "Wrong"
> d["key"] = "test"
>
> In order to print "test" using % substitution I can say
>
> print "%(key)s" % d
>
> Is there a way to print "Right" using % substitution?
>
> print "%((1,2))s" % d
>
> gives me "Wrong". Is there any syntax which will allow me to get
> "Right" using % substitution?
>
One way would be to make an adapter to convert that string to a tuple:
class adapter:
    def __init__(self, dc):
       self.dc = dc
    def __getitem__(self,item):
        return self.dc[eval(item)]

Then you could use this as:
print "%((1,2))s" % adapter(d)

I wouldn't actually recommend using eval in production code, due to the 
possible security issues, but I'm sure you could replace it with some 
more/better code. This is just an idea. 


-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to