When the amount of significant data is significant, this is the type of thing where a relational database comes in handy. A database with two columns, a key and a value and an index in the key column acts as a voice recorder. But you can also put an index in a value column to provide an efficient reverse lookup.
In your case, however, since the amount of data is small, I just make defaultdict and add (value, key) pairs.
reverse_lookup = defaultdict(list) for k, v in now_playing.items(): reverse_lookup[v].append(k)
And then you can ','.join() values ​​to create compound keys. Since these composite keys will be used for display, it seems that it is actually not for searching, I would just keep both the original dict and the reverse dict search in memory and use what you need when you need to search, The task of finding others players who play the same song as this one (and presumably synchronized) then include two searches, one forward and one backward, but they have hash tables, so the added value is minimal.
After some thought of other, more “interesting” ways to do this: you can pervert the disjoint set data structure to meet your needs. You will have a node for each player and a node for each song being played. Nodes are grouped by sets of songs, where one set contains both a node for a song and nodes for any players currently playing this song. If you put each set of nodes (song plus players) in a cyclically linked list while the overall data structure is properly maintained, you can start from any node and skip the list to iterate over both the song and the list of players who play this song.
The trick, of course, finds an efficient way to maintain this general data structure, i.e. Update looping lists as songs change. If the players are truly synchronized, it's as simple as replacing one node song with another, every time the whole group of players moves to the next track. But I can imagine that an application like the one you are creating often has to do other kinds of searches for which the structure of unrelated sets does not do you any good.
source share