Tuple-key dictionary in python: Accessing a whole block of entries

  dictionary, dictionary-comprehension, python

I am looking for an efficient python method to utilise a hash table that has two keys:
E.g.:

(1,5) --> {a}
(2,3) --> {b,c}
(2,4) --> {d}

Further I need to be able to retrieve whole blocks of entries, for example all entries that have "2" at the 0-th position (here: (2,3) as well as (2,4)).
In another post it was suggested to use list comprehension, i.e.:

sum(val for key, val in dict.items() if key[0] == 'B')

I learned that dictionaries are (probably?) the most efficient way to retrieve a value from an object of key:value-pairs. However, calling only an incomplete tuple-key is a bit different than querying the whole key where I either get a value or nothing. I want to ask if python can still return the values in a time proportional to the number of key:value-pairs that match? Or alternatively, is the tuple-dictionary (plus list comprehension) better than using pandas.df.groupby() (but that would occupy a bit much memory space)?

Source: Python Questions

LEAVE A COMMENT