How we can translate Python dictionary into C++?

A Python dictionary is a hash table data structure that stores key-value pairs. In C++, you can use the std::map or std::unordered_map containers to achieve similar functionality to Python dictionaries.

Using std::map in C++

The std::map container provides an ordered key-value mapping similar to Python dictionaries ?

#include <iostream>
#include <map>
using namespace std;

int main(void) {
    /* Initializer_list constructor */
    map<char, int> m1 = {
        {'a', 1},
        {'b', 2},
        {'c', 3},
        {'d', 4},
        {'e', 5}
    };
    
    cout << "Map contains following elements" << endl;
    for (auto it = m1.begin(); it != m1.end(); ++it)
        cout << it->first << " = " << it->second << endl;
    
    return 0;
}

The output of the above code is ?

Map contains following elements
a = 1
b = 2
c = 3
d = 4
e = 5

Python Dictionary Equivalent

The above C++ map is equivalent to this Python dictionary ?

m1 = {
    'a': 1,
    'b': 2,
    'c': 3,
    'd': 4,
    'e': 5
}

print("Dictionary contains following elements:")
for key, value in m1.items():
    print(f"{key} = {value}")
Dictionary contains following elements:
a = 1
b = 2
c = 3
d = 4
e = 5

Key Differences

Feature Python Dictionary C++ std::map
Declaration Dynamic typing Static typing required
Ordering Insertion order (Python 3.7+) Sorted by key
Syntax dict[key] = value map[key] = value

Using std::unordered_map

For better performance similar to Python dictionaries, use std::unordered_map ?

#include <iostream>
#include <unordered_map>
using namespace std;

int main(void) {
    unordered_map<string, int> scores = {
        {"Alice", 95},
        {"Bob", 87},
        {"Charlie", 92}
    };
    
    // Adding new element
    scores["David"] = 88;
    
    // Accessing elements
    cout << "Alice's score: " << scores["Alice"] << endl;
    
    return 0;
}

Conclusion

Use std::map for ordered key-value pairs similar to Python dictionaries. For hash table performance like Python dicts, prefer std::unordered_map. Both provide similar functionality with static typing requirements in C++.

---
Updated on: 2026-03-24T20:27:53+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements