Translating dict keys#
NOTE: For convenience, we’ll use a dummy fetcher used for testing to generate translation data instead of fetching real translations. Generated data is on the form <placeholder-name>-of-<id>, eg 'placeholder0-of-id0'.
Since we use fmt='{x}, {y}', translated values will take form 'x-of-<id>, y-of-<id>'.
[1]:
from id_translation import Translator
t = Translator(fmt="{x}, {y}")
/tmp/ipykernel_11399/1782748667.py:3: UserWarning: No fetcher given. Translation data will be automatically generated.
t = Translator(fmt="{x}, {y}")
Dummy data#
[2]:
a_dict = {f"k{i}": i for i in range(4)}
a_dict.keys()
[2]:
dict_keys(['k0', 'k1', 'k2', 'k3'])
Translation#
By default, the keys of a_dict would be used as the names. The Translator doesn’t know what to do with a dict_keys-object, and will raise an error if we give it one.
The solution is to convert the keys to a known type, then construct a dict with the new keys.
[3]:
translated_keys = t.translate(list(a_dict), names="name")
{tk: a_dict[k] for k, tk in zip(a_dict, translated_keys)}
[3]:
{'x-of-k0, y-of-k0': 0,
'x-of-k1, y-of-k1': 1,
'x-of-k2, y-of-k2': 2,
'x-of-k3, y-of-k3': 3}
We used a list here, but any supported ordered type will work. Do not use a set, as this may shuffle the keys.
[ ]: