Syntax for aliases to keys of python dictionaries

data = {k:True for k in (‘key1’, ‘key2’, ‘key3’)}

I think. I’m away from computer for weekend.

3 Likes

That is simply a dict comprehension you have done, but what if there were multiple keys that needed aliases, will have to combine the dict comprehensions I guess.

So, there is a chance of improving the readability by the suggested syntax. It’s just a simple idea only and I do understand that every idea need not be right or valid :heart:

I think “improves readability” is very much in the eye of the beholder here. I think it would be quite confusing.

2 Likes

Would you consider (ab)using a class for this?

class data:
    key1 = key2 = key3 = True
    a = b = c = "spam"

You can then get the __dict__ of that if you need it as an actual dictionary (filtering if needed).

3 Likes

I don’t think that solving this problem necessarily requires the addition of new syntax. I think the following code will allow for something very similar to your proposed syntax, will satisfy your problem constraints, AND doesn’t require heavy-handed changes to the language.

from collections import ChainMap
from collections.abc import Hashable, Mapping


def alias_flatten[V: Hashable](alias_mapping: Mapping[tuple[str, ...], V]) -> dict[str, V]:
  # Needed since ChainMap reverses the order of dictionaries when converted to a dict
  reversed_items = reversed(alias_dict.items())
  flattens = ({alias: value for alias in aliases} for aliases, value in reversed_items)  
  return dict(ChainMap(*flattens))


data = alias_flatten({
  ('key1', 'key2', 'key3'): True,  
  ('key4', 'key5', 'key6'): False
})
3 Likes

That would make it look like list has become hashable, and I would need to read the documentation to find out that it is not true.

3 Likes

You could add your aliases after the dict was established:

data = {
"colour": "blue is an example of a ...",
"trousers": "pants.jpg",
"quick": sum
}
data.update({
     'color': data['colour'],
     'pants': data['trousers'],
     'fast': data['quick'],
     'optimized': data['quick']
     })

which clearly shows the alias vs. base field relationship, and aliases actually refer to the same data as the base field.

2 Likes