data structures
programming
map implementation
multiple keys
duplicate question

How to implement a Map with multiple keys?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

In many programming scenarios, there's often a need to associate a value with not just a single key, but multiple keys. Traditional maps or dictionaries allow associating only one key per value. However, a "Map with multiple keys" can be quite useful when dealing with complex data structures or when you need to have multiple ways to query the same data.

This article will explore different methods to implement a map with multiple keys, delve into the technicalities of each approach, and provide examples to illustrate the concepts.

Methods to Implement a Map with Multiple Keys

1. Using Composite Keys

One straightforward approach to implement a map with multiple keys is to use composite keys. A composite key is a combination of multiple elements which uniquely identifies a value.

Example

Consider a scenario where you have a dataset of employees, and you want to map each employee's data by both their employee ID and email address.

python
1class CompositeKey:
2    def __init__(self, key1, key2):
3        self.key1 = key1
4        self.key2 = key2
5
6    def __hash__(self):
7        return hash((self.key1, self.key2))
8
9    def __eq__(self, other):
10        return (self.key1, self.key2) == (other.key1, other.key2)
11
12# Using the composite key
13employee_map = {}
14key = CompositeKey(employee_id, email)
15employee_map[key] = employee_data

2. Using Nested Data Structures

An alternative way to map multiple keys is to use nested dictionaries or maps. Each level of nesting corresponds to a part of the key.

Example

Continuing with the employee dataset example:

python
employee_map = {}
employee_map.setdefault(employee_id, {})[email] = employee_data

In this case, employee_id is the first-level key, and email is the second-level key.

3. Bi-Directional Maps

For some applications, you may require an efficient lookup of the key-value relationship in both directions. Python does not provide built-in bi-directional maps, but they can be implemented using two maps.

Example

python
1key_to_value = {}
2value_to_key = {}
3
4def add_mapping(key, value):
5    key_to_value[key] = value
6    value_to_key[value] = key
7
8def get_value(key):
9    return key_to_value.get(key)
10
11def get_key(value):
12    return value_to_key.get(value)

4. Using MultiKeyDict (Third-Party Libraries)

Several third-party libraries offer more comprehensive and feature-rich implementations for maps with multiple keys. One such library is multidict.

bash
pip install multidict

Example

python
1from multidict import MultiDict
2
3multi_key_map = MultiDict()
4multi_key_map.add(('key1', 'key2'), value)

5. Custom Data Structures

For ultimate flexibility, you can implement your custom data structure that can handle the complexity of mapping multiple keys to values efficiently.

Comparison Table of Methods

MethodDescriptionProsCons
Composite KeysCombines keys into one object to use as key.Simple implementation Direct usage of map functionsCustom hash/eq needed May confuse readability
Nested Data StructuresUses tiered dictionariesNative Python Easy to understandMore cumbersome lookups
Bi-Directional MapsCreates two-way mappingEfficient lookups in both directionsRequires maintaining two maps
MultiKeyDictUses third-party Python libraryReady-to-use Well-testedExternal dependency
Custom Data StructuresCustom implementation tailored to needsFully customizableComplex to implement Higher initial cost

Conclusion

Implementing a map with multiple keys may seem complex at first, but with various approaches at your disposal, you can select the method that best fits your needs. Whether it’s using composite keys, nested data structures, or a third-party library, understanding the strengths and limitations of each approach is vital for optimal performance and maintainability of your application.

Remember to consider factors like the complexity of your data, performance requirements, and ease of maintenance when selecting your implementation strategy.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.