The Wayback Machine - https://web.archive.org/web/20240818163941/https://www.geeksforgeeks.org/differences-between-array-and-dictionary-data-structure/
Open In App

Differences between Array and Dictionary Data Structure

Last Updated : 08 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Arrays:

  • The array is a collection of the same type of elements at contiguous memory locations under the same name. 
  • It is easier to access the element in the case of an array. 
  • The size is the key issue in the case of an array which must be known in advance so as to store the elements in it. 
  • Insertion and deletion operations are costly in the case of an array since the elements are stored at contiguous memory locations. 
  • No modification is possible at the runtime after the array is created and memory wastage can also occur if the size of the array is greater than the number of elements stored in the array.

Array representation:

C++




// C++ code for creating an array
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
   
    // Creating an array
    int arr[10]={1,2,3,4,5,6,7,8,9,10};
   
    // Printing the array
    for (int i = 0; i < 10; i++)
    {
        cout << arr[i] << " ";
    }
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
  public static void main (String[] args) {
 
    // Creating an array
    int arr[] = {1,2,3,4,5,6,7,8,9,10};
 
    // Printing the array
    for (int i = 0; i < 10; i++){
      System.out.print(arr[i]+" ");
    }
  }
}
 
// This code is contributed by aadityaburujwale.


Python




# Python code for Creation of Array
 
# importing "array" for array creation
import array as arr
 
# creating an array with integer type
a = arr.array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
 
# printing the array
for i in range(0, 10):
   
    # comma is used to generate spaces
    print(a[i]),


C#




// C# code for creating an array
using System;
 
// Driver Code
public class GFG {
 
    static public void Main()
    {
       
        // Declaring an array
        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
      
        // Printing the array
        for (int i = 0; i < arr.Length; i++) {
            Console.Write(arr[i] + " ");         
        }
    }
}


Javascript




<script>
     
    // Creating an array
    let arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
     
    // Printing the array
    for(let i = 0; i < 10; i++){
        document.write(arr[i] + " ");
    }
     
    // This code is contributed by lokesh
     
</script>


Output

1 2 3 4 5 6 7 8 9 10 

Time Complexity: O(1)
Auxiliary Space: O(1)

Dictionary:

  • 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++




// C++ program to demonstrate functionality of unordered_map
#include <iostream>
#include <unordered_map>
using namespace std;
 
int main()
{
     // Declare a Dictionary
    unordered_map<string, int> my_dict;
 
    // Adding Elements to the Dictionary
        my_dict["key1"] = 1;
        my_dict["key2"] = 2;
        my_dict["key3"] = 3;
 
    // Printing the Dictionary
    for (auto key : my_dict)
        cout << "Key: " << key.first << " Value: " << key.second << endl;
 
}
 
// This code is contributed by aadityaburujwale.


Java




/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
 
class GFG {
    public static void main (String[] args) {
        
          // Declare a Dictionary
        HashMap<String,Integer> my_dict = new HashMap<>();
       
         // Adding Elements to the Dictionary
        my_dict.put("key1", 1);
        my_dict.put("key2", 2);
        my_dict.put("key3", 3);
 
          // Printing the Dictionary
        for(String key:my_dict.keySet()) {
              System.out.println("Key: "+ key +", Value: " + my_dict.get(key));
            }
    }
}


Python




# Declaring and initializing a dictionary
my_dict = {
  "key1": 1,
  "key2": 2,
  "key3": 3
}
# Printing the dictionary
 
print(my_dict)


C#




using System;
using System.Collections.Generic;
public class GFG {
 
    static public void Main()
    {
     // Declare a Dictionary
        IDictionary<string, int> my_dict= new Dictionary<string, int>();
       
     // Adding Elements to the Dictionary
        my_dict.Add("key1", 1);
        my_dict.Add("key2", 2);
        my_dict.Add("key3", 3);
 
      // Printing the Dictionary
        foreach(var kvp in my_dict) {
          Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
    }
  }
}


Javascript




<script>
// Javascript program to demonstrate functionality of map
 
// Declare a Dictionary
var my_dict = new Map();
 
// Adding Elements to the Dictionary
my_dict.set("key1", 1);
my_dict.set("key2", 2);
my_dict.set("key3", 3);
 
// Printing the Dictionary
console.log(my_dict);
 
// This  code is contributed by Shubham Singh
</script>


Output

{'key3': 3, 'key2': 2, 'key1': 1}

Time Complexity: O(1)
Auxiliary Space: O(1)

Comparison Between Array and Dictionary:

# Array Dictionary 
1 Stores just a set of objects Represents the relationship between pair of objects
2

Lookup time is more in the  case of array O(N) 

where N is the size of the array

Lookup time is less compared to an array.

Generally, it is O(1) 

3 Elements are stored at contiguous memory locations. Elements may or may not be stored at a contiguous memory location.
4 Items are unordered, changeable, and do allow duplicates Items are ordered, changeable, and do not allow duplicates
5 Items are not represented as key: value pair Items are represented as key: value pair
6 The values in the array are of the same data type The values in dictionary items can be of any data type
7 Values can be accessed randomly without the need for any key To access a value the key is required 


Similar Reads

Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two types : 1. Static Data Structure 2. Dynamic Data
4 min read
Data Structure for Dictionary and Spell Checker?
Which data structure can be used for efficiently building a word dictionary and Spell Checker? The answer depends upon the functionalists required in Spell Checker and availability of memory. For example following are few possibilities. Hashing is one simple option for this. We can put all words in a hash table. Refer this paper which compares hash
5 min read
Implementation on Map or Dictionary Data Structure in C
C programming language does not provide any direct implementation of Map or Dictionary Data structure. However, it doesn't mean we cannot implement one. In C, a simple way to implement a map is to use arrays and store the key-value pairs as elements of the array. How to implement Map in C? One approach is to use two arrays, one for the keys and one
3 min read
Generate array having differences between count of occurrences of every array element on its left and right
Given an array A[] consisting of N integers, the task is to construct an array B[] such that for every ith index, B[i] = X - Y, where X and Y are the count of occurrences of A[i] after and before the ith index. Examples: Input: A[] = {3, 2, 1, 2, 3}Output: 1 1 0 -1 -1Explanation: arr[0] = 3, X = 1, Y = 0. Therefore, print 1. arr[1] = 2, X = 1, Y =
6 min read
Difference between data type and data structure
Data Type A data type is the most basic and the most common classification of data. It is this through which the compiler gets to know the form or the type of information that will be used throughout the code. So basically data type is a type of information transmitted between the programmer and the compiler where the programmer informs the compile
4 min read
Differences between Operational Database Systems and Data Warehouse
The Operational Database is the source of data for the information distribution center. It incorporates point by point data utilized to run the day to day operations of the trade. The information as often as possible changes as upgrades are made and reflect the current esteem of the final transactions. Operational Database Administration Frameworks
3 min read
Difference between Single Bus Structure and Double Bus Structure
1. Single Bus Structure: In a single bus structure, one common bus is used to communicate between peripherals and microprocessors. It has disadvantages due to the use of one common bus. 2. Double Bus Structure: In a double bus structure, one bus is used to fetch instructions while other is used to fetch data, required for execution. It is to overco
2 min read
Differences between Data paths
Prerequisite - ALU and Data Path In this section, we shall discuss the difference between data-paths. These data-paths are: Single CycleMultiple CyclePipeline In single cycle clock cycle time is long enough for instruction while in multi cycle and pipeline clock cycle time is short enough for the instructions. Now, the difference among them are giv
2 min read
Is array a Data Type or Data Structure?
What is Data Type? In computer programming, a data type is a classification of data that determines the type of values that can be stored, manipulated, and processed. It tells the computer what kind of data a particular variable or constant can hold, and what operations can be performed on that data. Common data types include integers, floating-poi
8 min read
Data Structure Alignment : How data is arranged and accessed in Computer Memory?
Data structure alignment is the way data is arranged and accessed in computer memory. Data alignment and Data structure padding are two different issues but are related to each other and together known as Data Structure alignment. Data alignment: Data alignment means putting the data in memory at an address equal to some multiple of the word size.
4 min read
Difference between Active and Passive Data Dictionary
Prerequisite -Short note on Data DictionaryData Dictionary is a part of disk storage that is heavily used to store metadata of the structure of the database. For the efficient implementation of these data dictionaries, great importance should be given to developing a good design. The data dictionary can be defined as a collection of information of
4 min read
Generate a permutation of first N natural numbers from an array of differences between adjacent elements
Given an array arr[] consisting of (N - 1), the task is to construct a permutation array P[] consisting of the first N Natural Numbers such that arr[i] = (P[i +1] - P[i]). If there exists no such permutation, then print "-1". Examples: Input: arr[] = {-1, 2, -3, -1}Output: 4 3 5 2 1Explanation:For the array {4, 3, 5, 2, 1}, the adjacent difference
8 min read
Minimize increments required to make differences between all pairs of array elements even
Given an array, arr[] consisting of N integers, the task is to minimize the number of increments of array elements required to make all differences pairs of array elements even. Examples: Input: arr[] = {4, 1, 2}Output: 1Explanation: Operation 1: Increment arr[1] by 1. The array arr[] modifies to {4, 2, 2}.All pairs: (4, 2) ? difference = 2(4, 2) ?
5 min read
Maximum sum of absolute differences between distinct pairs of a triplet from an array
Given an array arr[] consisting of N integers, the task is to find the maximum sum of absolute differences between all distinct pairs of the triplet in the array. Examples: Input: arr[] = {1, 2, 3, 4}Output: 6Explanation:The valid triplet is (1, 3, 4) as sum = |1 - 4| + |1 - 3| + |3 - 4| = 6, which is the maximum among all the triplets. Input: arr[
5 min read
Minimum sum of absolute differences between pairs of a triplet from an array
Given an array A[] consisting of positive integers, the task is to find the minimum value of |A[x] - A[y]| + |A[y] - A[z]| of any triplet (A[x], A[y], A[z]) from an array. Examples: Input: A[] = { 1, 1, 2, 3 }Output: 1Explanation:For x = 0, y = 1, z = 2|A[x] - A[y]| + |A[y] - A[z]| = 0 + 1 = 1, which is maximum possible Input : A[] = { 1, 1, 1 }Out
5 min read
Minimum number of swaps required to minimize sum of absolute differences between adjacent array elements
Given an array arr[] consisting of N distinct positive integers, the task is to find the minimum number of elements required to be swapped to minimize the sum of absolute difference of each pair of adjacent elements. Examples: Input: arr[] = {8, 50, 11, 2}Output: 2Explanation:Operation 1: Swapping of elements 8 and 2, modifies the array arr[] to {2
15 min read
Minimum sum of all differences between unique pairs in the Array
Given an array arr[] consisting of N integers, the task is to find the minimum sum of all absolute differences between unique pairs of elements in the array after updating the array arr[]. To update the array, any two elements from the array can be chosen in any order. 1 is subtracted from the first element and added to the second element. This ste
7 min read
Minimize sum of absolute differences between given Arrays by replacing at most 1 element from first Array
Given two arrays a[] and b[] of equal size. The task is to calculate the minimum sum of absolute differences for each index. It is allowed to replace at most 1 element of the first array with any value from the first array itself. Example: Input: a[] = {1, 9, 4, 2}, b[] = {2, 3, 7, 1}Output: 6Explanation: Change the value of a[1] = 4 or 2. The mini
9 min read
Maximize difference between the sum of absolute differences of each element with the remaining array
Given an array arr[] consisting of N integers, the task is to maximize the difference between the sum of absolute difference of an element with the remaining elements in the array. Examples: Input: arr[] = {1, 2, 4, 7}Output: 6Explanation:For i = 1, |1 - 2| + |1 - 4| + |1 - 7| = 1 + 3 + 6 =10.For i = 2, |2 - 1| + |2 - 4| + |2 - 7| = 1 + 2 + 5 = 8.F
12 min read
Sum of squares of differences between all pairs of an array
Given an array arr[] of size N, the task is to compute the sum of squares of differences of all possible pairs. Examples: Input: arr[] = {2, 8, 4}Output: 56Explanation: Sum of squared differences of all possible pairs = (2 - 8)2 + (2 - 4)2 + (8 - 4)2 = 56 Input: arr[] = {-5, 8, 9, -4, -3}Output: 950 Brute Force Approach: The brute force approach to
9 min read
Internal Structure of Python Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized The dictionary consists of a number of buckets. Each of these buckets cont
3 min read
Similarities and Differences between Ruby and C language
Similarities between Ruby and C There are many similarities between C and Ruby, and some of them are: Like C, in Ruby also… A programmer is able to program procedurally if they like to do. But still, behind the scenes, it will be object-oriented.Both the languages have the same operators, for example, compound assignment and bitwise operators. But
3 min read
Similarities and Differences between Ruby and C++
There are many similarities between C++ and Ruby, some of them are: Just like C++, in Ruby… As in C++, public, private, and protected works similarly in Ruby also .Inheritance syntax is still only one character, but it’s &lt; instead of : in Ruby.The way ‘namespace’ is used in C++, in the similar way we may put our code into “modules” in ruby.There
3 min read
What are the differences between bitwise and logical AND operators in C/C++?
A Bitwise And operator is represented as '&amp;' and a logical operator is represented as '&amp;&amp;'. The following are some basic differences between the two operators. a) The logical and operator '&amp;&amp;' expects its operands to be boolean expressions (either 1 or 0) and returns a boolean value. The bitwise and operator '&amp;' work on Inte
4 min read
Find the array element having minimum sum of absolute differences with all other array elements
Given an array arr[] of size N, the task is to find the minimum sum of absolute differences of an array element with all elements of another array. Input: arr[ ] = {1, 2, 3, 4, 5}, N = 5Output: 3Explanation: For arr[0](= 1): Sum = abs(2 - 1) + abs(3 - 1) + abs(4 - 1) + abs(5 - 1) = 10.For arr[1](= 2): Sum = abs(2 - 1) + abs(3 - 2) + abs(4 - 2) + ab
4 min read
Difference between Database and Data Structure
1. Database : A Database is a collection of data that is stored in an organized fashion in a table containing rows and columns using a software package known as Database Management System (DBMS). DBMS is used to modify, define, manipulate and manage data. Some examples of DBMS are : MySQL, Oracle Database and Microsoft Access. 2. Data Structure : I
2 min read
Android Studio Project Structure VS Eclipse Project Structure
Eclipse is a standard package that is ideal for java and plug-in development, as well as introducing new plugins. Eclipse is mostly used for Java because it is basically developed in Java. One of the reasons Eclipse is well-known for its Java IDE is because of this. To personalize the environment, Eclipse includes its own workspace and a flexible p
4 min read
Differences between Flatten() and Ravel() Numpy Functions
We have two similar kinds of ways to convert a ndarray to a 1D array of Flatten() and Ravel() Numpy function in Python programming language. Example of Flatten() Numpy function Here, we will create a Numpy array, and then by using flatten function we have changed the element in the flattened 1D NumPy array. C/C++ Code import numpy as np # Create a
3 min read
Differences between number of increasing subarrays and decreasing subarrays in k sized windows
Given an array of integers and k, find the difference between the number of the strictly increasing number of subarrays (of size more than one) and the number of the strictly decreasing subarray in the window of size k. Examples: Input : nums = {10, 20, 30, 15, 15}; k = 3; Output : 3, 0, -1 Explanation For the first window of [10, 20, 30], there ar
8 min read
Differences between Computer Architecture and Computer Organization
Computer Architecture is a functional description of requirements and design implementation for the various parts of a computer. It deals with the functional behavior of computer systems. It comes before the computer organization while designing a computer. Computer architecture and computer organization are related but distinct concepts in the fie
3 min read
three90RightbarBannerImg