Pull to refresh

Dictionary/Map

Algorithms

A basic data structure in computer science is the “associative array” known as a “map”. This structure is called a “dictionary”. Dictionaries are being used when you have key-value pairs of the information. Inputs are called keys, and outputs are called values. A dictionary is the abstract data type that can store elements so that they can be positioned quickly by using keys. Dictionary is like a container that will have a searchable assortment of items. Each item in the dictionary is stored as a key-value pair. In a dictionary, we can store multiple items with the same key.

Dictionary consists of multiple elements in terms of key and value pair. Both key and value are considered as one single pair. This is called mapping. Elements of the dictionary are enclosed in curly brackets in terms of key and value pairs. Dictionaries enable us to work with key-value pairs. Key-value pairs are two linked values where the key is the unique identifier where we can discover our data and the value is that the information.

Dictionary maps key-value pairs. It is a collection data type that has key-value pairs. A dictionary does not contain any duplicate members.

It is unordered and stores data values like a map. Thus, it is similar to the real-life dictionary with distinct key values. In a dictionary, we use keys as indexes to access elements.

The dictionary helps us to organize the collection of data. It is a special data type. Its syntax is:

dictionary = { ‘Key’: ‘Value’ , ‘Key’ : ‘Value’ }

This dictionary has two items separated by commas, and every single item is a key-value pair split up by a colon.

Data of key must be of immutable type:

  1. String

  2. Number

  3. Tuples

If the key is of a mutable type, it will show an error. It is similar to associative arrays in other programming languages.

Example

A telephone dictionary is an example of a dictionary data structure. A telephone dictionary is organized in the form of key-value items. It contains the name of the resident and phone number. And we can call name as key and phone number as a value.

We have another example in which the dictionary contains three items (key, value) pairs separated by commas (, ) and enclosed by curly brackets. Keys are Name, John, and Department. While values are xyz, 973, and ECE.

Dictionary = { “Name” : “xyz” , “John” : 973 , “Department”: “ECE” }

Operations

It has the following major operations:

  1. Addition

  2. Modification

  3. Deletion

Addition

Let us consider a dictionary ‘D’ having three key-value pairs.

D = { ‘Name’ : ‘xyz’ , ‘Number’ : 578 , ‘Branch’ : ‘ECE’ }

In this dictionary, the keys are Name, Number, and Branch. While values are xyz, 578, and ECE. If we want to add new key-value pair to this dictionary, then we will use the following syntax:

Modify

We use an existing key to modify the dictionary.

For dictionary D, if we want to modify the ‘Course’ value with a new value, then.

Deletion

It deals with the existing item in the dictionary. For deleting one or more elements from the dictionary, we use the ‘del keyword’. Its syntax is:

And ‘clear( )’ function is used to clear all the key-value pairs from the dictionary. Its syntax is

D.clear( )

Let us consider an example to comprehend the above operations. For this purpose, we consider a dictionary ‘A’ and enclose it in curly brackets. It contains three key-value pairs. We use the colon ( : ) operator to specify the key-value pair. And comma ( ) is used to separate multiple elements. We can access the elements by the help of keys.

Output will be:

{ ‘Bike’ : ’Honda ’ , ‘ Model ’ : ‘CD70 ’ , ’Color’ : ’Red’ }print ( A [ ‘Model’ ]) print ( A [ ‘Color’ ])

Output will be:

CD70Red

To add one more element:

A[ ‘ RegNumber ’] = 1257print (A)

Output will be:

{ ‘Bike’ : ’Honda ’ , ‘ Model ’ : ‘CD70 ’ , ’Color’ : ’Red’, ‘ RegNumber ’ : 1257 }

Now, to delete one element from dictionary

Output will be:

 { ‘Bike’ : ’Honda ’ , ‘ Model ’ : ‘CD70 ’ , ‘ RegNumber ’ : 1257 }

To clear elements from the dictionary

Output will be:

Creation of Dictionary

While creating a dictionary, we must know that a key can be any immutable object like numbers, strings, or tuples. Though, they cannot be objects that can be altered like lists. And keys must be unique for identifications. The vacant dictionary is created as:

To create a dictionary with multiple value pairs, we usually use the following syntax:

The key and value can be any sort of data.

Similarly, we can create a dictionary using the dictionary function. For this purpose, we can use the function ‘dict ( ) ’. In this function, we pass the pairs of key and value in Tuple such as

dict ( [(K1 , V1)  , (K2,V2),……., (Kn,Vn)  ]  )

We can also establish a dictionary by using comprehension. In this, we have to specify an expression, iteration, and condition. The syntax for creating a dictionary using comprehension is:

Accessing of Dictionary Items

Dictionaries are enhanced to get values when the keys are known. In the dictionary, keys are used as indices. Thus, we can access the corresponding values of the dictionary with the help of keys. For example, consider a dictionary that contains 3 keys that are Name, Department, and Reg Number. With the assistance of these keys, we can access values in this dictionary.

If we try to access the key that is not available in the dictionary, there will be an error showing that the key is not found.

Methods In Dictionary

A dictionary contains key-value pair, which is available in the form of a tuple. Following are the different methods in the dictionary:

copy( )

This function is used to copy the key-value pairs into another variable.

Let us consider a dictionary ‘D’ that contains three pairs having key and value.

clear( )

This function will clear all the items in the dictionary. It will give an empty dictionary at the output.

items( )

It will display all the key-value pairs available in the dictionary. We will not take any argument in this. For the above dictionary ‘D’, we can write this as:

D.items ( )

keys( )

In the dictionary, the first attribute item is key, and the second is value. The purpose of a key ( ) function is to give all the keys available in the dictionary. Here we will give no argument. Its syntax is:

D.keys ( )

values( )

Its purpose is to display all the values in the dictionary. It does not require any argument. Its syntax is:

D.values( )

update( )

It is used to insert one or more key-value pairs into the existing dictionary. This method will take the argument to the dictionary. Its syntax is:

pop( )

Its purpose is to remove or delete an item from the dictionary. It will return the value of a key that was deleted. Its syntax is:

The value is an optional argument in this syntax. It means that if you only give a key as an argument, then only that argument will be deleted from the dictionary, and the corresponding value will be returned.

Let us take a dictionary ‘D’.

And we pass the argument 'Course'. Then this key argument will be deleted, and the corresponding ‘DSP’ argument will be returned.

popitem( )

It will remove the recently inserted item from the array. And the value of deleted key-value pair will be returned. It does not need any argument. For the above dictionary ‘D’, its syntax is:

D.popitem( )

get( )

It is used to give back the value of the given key. Its syntax is:

For the above dictionary D, we can write it as:

D.get(''RegNumber'')

And it will return the value ‘973’ corresponding to ‘RegNumber’.

fromkeys( )

It will take two arguments. One is a tuple of keys. . While the next argument is the value that is applied to all the values of the tuple. The tuple is a constant, and all the keys can be formed as tuples. And these tuples can be passed as one argument. Its syntax is:

Where ‘t’ is a tuple having keys, and 'v' is the value.

                                                                        D.fromkeys(t,0)

setdefault( )

It will take key and value as arguments. If this new key is not available in the dictionary, it will be inserted into the dictionary. If this new key is available in the dictionary, then there will be no change. Its syntax is:

The output will be:

{ “Name” : “ xyz” , “RegNumber” : 973 , “Course” : “DSP” , “Age” , 23 }

Implementation

To implement different methods of the dictionary, a dictionary ‘D’ will be created. Dictionary elements are key-value pairs. There are three key-value pairs.

D = { "name" : "abc", "RegNumber": 973, "Course": "DSP" }
print(D);
{ "name" : "abc", "RegNumber": 973, "Course": "DSP" }

c = D.copy() //create the copy of dictionary
print (c)
{ "name": "abc", "RegNumber": 973, "Course": "DSP" }

c.clear() //clear all key value pairs from the dictionary
print(c)
{} 

D.items() //display all the item from the dictionary
dict_items([("name", "abc"), ("RegNumber", 973), ("Course", "DSP")])

D.keys() //to access all the keys from the dictionary
dict_keys(["name", "RegNumber", "Course"])

D.values() //to access all the values from the dictionaryprint(D)
dict_values(["abc", 973, "DSP"])
print(D)
{ "name": "abc", "RegNumber": 973, "Course": "DSP" }

D.get("name")  //to get a value for a particular key
"abc"

D.pop("Course", "DSP")  //to remove key value pair
"DSP"

print(D)
{ "name": "abc", "RegNumber": 973 }

D.popitem()  //to delete recently inserted item("RegNumber", 973 )print(D)
{ "name": "abc" }

D.fromkeys( "name" ,"abc" )
{ "n": "abc", "a": "abc", "m": "abc", "e": "abc" }
a = ("e", "b", "c")

D.fromkeys(a , "abc")
{ "e" : "abc" , "b": "abc" , "c": "abc" }

print(D)
{ "name" : "abc" }

D.update ({ "RegNumber" : 973 , "Course" : "DSP"})  //to update items in dictionary
print(D)
{ "name" : "abc", "RegNumber" : 973  , "Course" : "DSP" }

D.setdefault("RegNumber", 898 )
973

D.pop("RegNumber")
973

print(D)
{ "name": "abc", "Course" : "DSP" }
D.setdefault( "RegNumber", 898 ) 
898

print(D)
{ "name": "abc" ,"Course" : "DSP", "RegNumber" : 898 }

Code Implementation of Dictionary

Dictionaries play an important role in optimizing the time complexity of different tasks provided reasonable information.

Example: Telephone directory.

Let we have a list of names of people and their phone numbers respectively, and we have to make a telephone directory.

Cell1:

now in order to find the User4 phone number it will only take 1-time access to reach respective user' number if we will convert the lists to dictionary

Lists are represented as a dictionary

dict={'User1':'+921','User2':'+922','User3':'+923','User4':'+924'}

Find the phone number of the fourth user

Search_User='User4'
print ("The phone number of ",Search_User,"is ", dict[Search_User])

Output:

Cell2:

Adding new number and users to the telephone directory

dict['User5']='+925'
print(dict)

Output:

{'User1': '+921', 'User2': '+922', 'User3': '+923', 'User4': '+924', 'User5': '+925'}

Cell3:

Edit the number of a user

dict['User1']='+92111'
print(dict)

Output:

{'User1': '+92111', 'User2': '+922', 'User3': '+923', 'User4': '+924', 'User5': '+925'}

Cell4:

Deleting The number of a user

let we want to delete the User5 phone number from our contact list

del dict['User5']
print(dict)

Output:

{'User1': '+92111', 'User2': '+922', 'User3': '+923', 'User4': '+924'}
Tags:mapdictionary
Hubs: Algorithms
Rating 0
Views548

Popular right now

Аналитик
from 80,000 to 200,000 ₽Call SolutionsСанкт-Петербург
Distributed Systems Engineer
from 8,000 $Cube.jsRemote job
Product Owner/ Руководитель проекта
from 200,000 to 250,000 ₽ЛИЦАМоскваRemote job
Scala developer
from 280,000 ₽Waves EnterpriseМоскваRemote job

Top of the last 24 hours