- A dictionary is a collection of data values.
- It holds a key: value pair in which we can easily access a value if the key is known.
- It improves the readability of your code and makes it easier to debug
- It is fast as the access of a value through a key is a constant time operation
Dictionary representation:
C++
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<string, int > my_dict;
my_dict[ "key1" ] = 1;
my_dict[ "key2" ] = 2;
my_dict[ "key3" ] = 3;
for ( auto key : my_dict)
cout << "Key: " << key.first << " Value: " << key.second << endl;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args) {
HashMap<String,Integer> my_dict = new HashMap<>();
my_dict.put( "key1" , 1 );
my_dict.put( "key2" , 2 );
my_dict.put( "key3" , 3 );
for (String key:my_dict.keySet()) {
System.out.println( "Key: " + key + ", Value: " + my_dict.get(key));
}
}
}
|
Python
my_dict = {
"key1" : 1 ,
"key2" : 2 ,
"key3" : 3
}
print (my_dict)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static public void Main()
{
IDictionary< string , int > my_dict= new Dictionary< string , int >();
my_dict.Add( "key1" , 1);
my_dict.Add( "key2" , 2);
my_dict.Add( "key3" , 3);
foreach ( var kvp in my_dict) {
Console.WriteLine( "Key: {0}, Value: {1}" , kvp.Key, kvp.Value);
}
}
}
|
Javascript
<script>
var my_dict = new Map();
my_dict.set( "key1" , 1);
my_dict.set( "key2" , 2);
my_dict.set( "key3" , 3);
console.log(my_dict);
</script>
|
Output
{'key3': 3, 'key2': 2, 'key1': 1}
Time Complexity: O(1)
Auxiliary Space: O(1)
Differences between Array and Dictionary Data Structure
Contact Us