Daniel Krenn <[email protected]> writes:
> Is there something like an "infinite dictionary" in Sage/Python?
>
> More precisely, is there something where
> - i can put in values like in a dictionary,
> - but maybe also a function which tells me how to map a key to a value,
> - and maybe also something that maps a key to a (finite) set of keys and then
> gives the corresponding value?
> Formulated in another way, what I want to have is the following "thing":
> I initialize it in a way (give values, functions, whatever) and then it just
> gives me for each key a value (on request).
Sure, this is not difficult with the way that Python implements
dictionary-like objects::
sage: class dictlike(object):
....: def __getitem__(self, key):
....: if isinstance(key, int):
....: return key^2
....: elif isinstance(key, str):
....: return key[::-1]
....: else:
....: return "??? {0} ???".format(key)
....:
sage: foo = dictlike()
sage: foo[3] # an Integer object
'??? 3 ???'
sage: foo[3r] # an int object
9
sage: foo["Puuha-Pete"]
'eteP-ahuuP'
Hope that helps.
-Keshav
----
Join us in #sagemath on irc.freenode.net !
--
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org