0

I want to create a dictionary in the form of:

my_dict = dict.fromkeys((["name", "id"] , "value"), 10)

So that in order to access element 10, I could either type:

my_dict["name","value"] >> 10

or

mydict["id", "value"] >> 10

I think this is pretty explanatory, two keys are mandatory, but for the first one you can choose which one to use. Is this possible?

D1X
  • 5,025
  • 5
  • 21
  • 36
  • 3
    Something like this `my_dict = {("id", "value"): 10, ("name", "value"): 10}` is the closest you can get without overriding methods. – Eli Korvigo Nov 03 '16 at 12:19
  • According to this [documentation](https://docs.python.org/2/tutorial/datastructures.html#dictionaries): *..keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples;* – maze88 Nov 03 '16 at 12:20
  • @EliKorvigo I want to create the keys dinamically by using a for loop, is this possible using your syntax? – D1X Nov 03 '16 at 12:20
  • `keys = [("name, "value"), ("id", "value")]; value = 10; my_dict = {}; for key in keys: my_dict[key] = value`. Though this looks ugly as hell. I suppose your design is not good at all. – Eli Korvigo Nov 03 '16 at 12:23
  • Possible duplicate of [Dictionary with some mandatory keys as function input](https://stackoverflow.com/questions/21014761/dictionary-with-some-mandatory-keys-as-function-input) – Stevoisiak Feb 28 '18 at 20:29

1 Answers1

0

Instead of hacking dict's interfaces or writing ugly stuff (as I've shown in the comments), you'd better change your design a bit:

def get_any(dictionary, keys):
    try:
        return next(filter(bool, (dictionary.get(key) for key in keys)))
    except StopIteration:
        raise KeyError

group = ("name", "value"), ("id", "value")
dict = {("id", "value"): 10}
get_any(dict, group)

This way you can find values for a group of keys, given at least one is present in the dictionary.

Eli Korvigo
  • 10,265
  • 6
  • 47
  • 73