0

Given the following dict

CV = { a: [a, b], b: [b, c], c: [c], d: [d] }

Let's say I am lazy and I want to have the dictionary return a value that references the key, something like

CV = { a: [a, b], b: [b, c], _: [_] }

Is this possible?

Hoang
  • 167
  • 3
  • 12
  • No, it is not... – deceze May 12 '22 at 09:31
  • Honestly I don't understand what you're asking :( – gimix May 12 '22 at 09:34
  • What's the question? If a, b, c and _ all exists, that CV line works – Koen G. May 12 '22 at 09:35
  • I suppose you could use something like a dict comprehension to write all the reflexive entries somewhat shorter. – Luatic May 12 '22 at 09:36
  • 2
    If you want to have a dictionary that for a missing key `k` returns `[k]` by default, you can do that by subclassing `dict`. Is that what you are asking for? – khelwood May 12 '22 at 09:37
  • 2
    Or use `dict.get(key, [key])`. – isaactfa May 12 '22 at 09:39
  • @khelwood Yes, I am looking for a way to get a dict to return some default values implicitly. Maybe that's a bit too much for a dict, so I'm thinking about wrapping it in a function that handles the default part, instead of using `.get()` and repeat the default return value multiple times. – Hoang May 12 '22 at 09:48
  • 1
    So if I understand correctly you want, for missing keys, to return a value based on a function called with the missing key? In that case look here: [python-dict-with-default-value-based-on-key](https://stackoverflow.com/questions/65901825/python-dict-with-default-value-based-on-key) – Koen G. May 12 '22 at 09:52

1 Answers1

1

Use the .get() method and set the key as the default values as well:

>>> my_dict = {"a": [1], "b": [2]}
>>> my_dict.get("a", ["a"])
[1]
>>> my_dict.get("c", ["c"])
['c']
>>>
Tzane
  • 2,752
  • 1
  • 10
  • 21