On 13 September 2013 22:40, Ethan Furman <et...@stoneleaf.us> wrote: > On 09/13/2013 06:25 PM, MRAB wrote: >> >> On 14/09/2013 01:49, Steven D'Aprano wrote: >>> >>> >>> Is it more common to want both the canonical key and value at the same >>> time, or to just want the canonical key? My gut feeling is that I'm >>> likely to have code like this: >>> >>> >>> d = TransformDict(...) >>> for key in data: >>> key = d.get_canonical(key) >>> value = d[key] >>> print("{}: {}".format(key, value)) >>> >> I think I must be missing something. I thought that iterating over the >> >> dict would yield the original keys, so if you wanted the original key >> and value you would write: >> >> for key, value in data.items(): >> print("{}: {}".format(key, value)) > > > Well, that's certainly how I would do it. ;)
I hope you are aware that this pattern does not help when one wants _one_ canonical key having a non-canonical one, besides having to linearly walk through all keys and check the "__transform__" to each one. I mean - given no function to retrieve the canonical key, one would have to resort to: my_key = data.__transform__(given_key) for key, value in data.items(): if data.__transform__(key) == my_key: .... WHich would defeat not only the purpose of a Transform dict, but the purpose of a dict alltogether. (of course, the one obvious way to do it would be to have the original key stored along the value - which is just a bit less silly than the example above) OTOH, having a `get_canonical_key` method or similar seens trivial enough- if the only provided method retrieves the value as well, it would not be that bad. > > > >> and if you wanted the transformed key you would apply the transform >> function to the key. > > > Indeed. The question is: how? It is entirely possible that your function > has a TransformDict alone, and no memory of the transform function used to > create the dict... > > If the key transform function were saved directly on the TransformDict > instance as, say, .transform_key, then problem solved. > > -- > ~Ethan~ > > _______________________________________________ > Python-Dev mailing list > Python-Dev@python.org > https://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: > https://mail.python.org/mailman/options/python-dev/jsbueno%40python.org.br _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com