Bidirectional 1 to 1 Dictionary in C
Codemia Knowledge Hub ·
Introduction
In software development, dictionaries (or maps) are often used to facilitate fast lookups between keys and values. Sometimes, applications require mapping in both directions, which a typical dictionary does not naturally support because lookups inherently favor one direction - from a key to a value. This article explores how a Bidirectional 1-to-1 Dictionary can be implemented in C#, providing an efficient way to access elements in both directions while ensuring bijective relationships.
Concept of a Bidirectional Dictionary
A bidirectional dictionary ensures a one-to-one mapping between two sets of data, allowing for lookup in either direction without the need for duplicate data structures. This means that given a key, you can find a corresponding value, and given a value, you can find its associated key.
Key Characteristics:
- Bijective Mapping: Every key has a unique value, and every value has a unique key.
- Constant Time Complexity: Both key-to-value and value-to-key lookups should ideally have O(1) access time.
- Synchronous Update: Changes in one direction should reflect immediately in the other direction.
Implementation in C#
Primary Data Structures
To implement a bidirectional dictionary in C#, we can utilize two dictionaries: one for the key-to-value mapping and another for the value-to-key mapping. Below is an example implementation:
- Add(T1 key, T2 value): This method establishes a mapping between a key and a value in both directions while ensuring no duplicates exist.
- GetValue(T1 key) and GetKey(T2 value): Both methods retrieve elements in constant time, enabling efficient lookups.
- RemoveByKey(T1 key) and RemoveByValue(T2 value): These methods remove the mapping in both dictionaries, keeping data consistent.
- Count: This property returns the number of elements in the dictionary, mirroring both maps.
- Text Processing: Mapping between words and identifiers or codes.
- Systems with Inverse Relationships: Associating foreign language words with their native translations.
- Data Synchronization: Keeping corresponding data elements in sync.
Related reading
- Big-O summary for Java Collections Framework implementations?
- Big O of JavaScript arrays
- Binary Search in 2D Array
- Binary search to find the rotation point in a rotated sorted list
- Bind TextBox on Enter-key press
- Bind to a method in WPF?
- Binary search vs binary search tree
- Binary Space Partitioning Data Structure For Donut 2D Space

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 courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.