Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python `dict` indexed by tuple: Getting a slice of the pie

Let's say I have

my_dict = {
  ("airport", "London"): "Heathrow",
  ("airport", "Tokyo"): "Narita",
  ("hipsters", "London"): "Soho"
}

What is an efficient (no scanning of all keys), yet elegant way to get all airports out of this dictionary, i.e. expected output ["Heathrow", "Narita"]. In databases that can index by tuples, it's usually possible to do something like

airports = my_dict.get(("airport",*))

(but usually only with the 'stars' sitting at the rightmost places in the tuple since the index usually is only stored in one order).

Since I imagine Python to index dictionary with tuple keys in a similar way (using the keys's inherent order), I imagine there might be a method I could use to slice the index this way?

Edit1: Added expected output

Edit2: Removed last phrase. Added '(no scanning of all keys)' to the conditions to make it clearer.

like image 243
Michel Müller Avatar asked Dec 24 '22 18:12

Michel Müller


1 Answers

The way your data is currently organized doesn't allow efficient lookup - essentially you have to scan all the keys.

Dictionaries are hash tables behind the scenes, and the only way to access a value is to get the hash of the key - and for that, you need the whole key.

Use a nested hierarchy like this, so you can do a direct O(1) lookup:

my_dict = {
  "airport": {
     "London": "Heathrow",
     "Tokyo": "Narita",
  },
  "hipsters": {
     "London": "Soho"
  }
}
like image 149
Karoly Horvath Avatar answered Dec 30 '22 16:12

Karoly Horvath