Dictionary in Python

Dictionary in Python

Dictionary Python 

pyqt tutorial python python 3 python 3 tutorial python basic programs python classes near me python coding python course fees python data analysis python django tutorial python ide python list python machine learning python online python online training python programming python programming for beginners

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 single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to make it more optimized and simpler.

Note – Keys in a dictionary doesn’t allows Polymorphism.

Polymorphism : 

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

we will discuss about this topic in our upcoming Articles.


Creating a Dictionary

In Python, a Dictionary can be created by placing sequence of elements within curly {} braces, separated by ‘comma’, this is the syntax mainly, dictionary holds a pair of values, one being the Key and the other corresponding pair element being its Key:value. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.

Note –

The Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.

# Creating a Dictionary 
# with Integer Keys
Dict = {1: 'Code', 2: 'For', 3: 'Job'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
  
# Creating a Dictionary 
# with Mixed keys
Dict = {'Name': 'Code', 1: [1, 2, 3, 4, 5]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)


output :

Dictionary with the use of Integer Keys: 
{1: 'Code', 2: 'For', 3: 'Job'}

Dictionary with the use of Mixed Keys: 
{'Name': 'Code', 1: [1, 2, 3, 4, 5]}


Note - 

Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing to curly braces{}.

# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
  
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Code', 2: 'For', 3:'Job'})
print("\nDictionary with the use of dict() method : ")
print(Dict)
  
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Code'), (2, 'Dudle')])
print("\nDictionary with each item as a pair: ")
print(Dict)


output :

Empty Dictionary: 
{}

Dictionary with the use of dict() method : 
{1: 'Code', 2: 'For', 3: 'Job'}

Dictionary with each item as a pair: 
{1: 'Code', 2: 'Dudle'}


Nested Dictinary :

A Dictionary within the Dictionary by using of same curly braces in the curly braces

# Creating a Nested Dictionary 
# as shown in the below image
Dict = {1: 'Code', 2: 'For'
        3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'CodeDudle'}}
  
print(Dict


output :

{1: 'Code', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'CodeDudle'}}


Adding elements to a Dictionary

In Python Dictionary, Addition of elements can be done in multiple ways. One value at a time can be added to a Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing value in a Dictionary can be done by using the built-in update() method. Nested key values can also be added to an existing Dictionary.


Note- 

While adding a value, if the key value already exists, the value gets updated otherwise a new Key with the value is added to the Dictionary.

Lets see by a code

# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
  
# Adding elements one at a time
Dict[0] = 'Code'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
  
# Adding set of values 
# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
  
# Updating existing Key's Value
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
  
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Code'}}
print("\nAdding a Nested Key: ")
print(Dict)


output :

Empty Dictionary: 
{}

Dictionary after adding 3 elements: 
{0: 'Code', 2: 'For', 3: 1}

Dictionary after adding 3 elements: 
{0: 'Code', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}

Updated key value: 
{0: 'Code', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}

Adding a Nested Key: 
{0: 'Code', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Life', '2': 'Code'}}}


Accessing elements from a Dictionary

In order to access the items of a dictionary refer to its key name.Key can be used inside square brackets to access the elements inside the dictionary.


# Python program to demonstrate  
# accessing a element from a Dictionary 
  
# Creating a Dictionary 
Dict = {1: 'Code', 'name': 'For', 3: 'Job'}
  
# accessing a element using key
print("Accessing a element using key:")
print(Dict['name'])
  
# accessing a element using key
print("Accessing a element using key:")
print(Dict[1])

output :

Accessing a element using key:
For
Accessing a element using key:
Code


There is another method available for accessing the elements inside the dictionary called get().

# Creating a Dictionary 
Dict = {1: 'Code', 'name': 'For', 3: 'Job'}
  
# accessing a element using get()
# method
print("Accessing a element using get:")
print(Dict.get(3))


output :

Accessing a element using get:
Job


Accessing element of a nested dictionary

In order to access the value of any key in nested dictionary, use indexing [] syntax. This helps to access the elements in nested dictionary.

# Creating a Dictionary
Dict = {'Dict1': {1: 'Code'},
        'Dict2': {'Name': 'For'}}
  
# Accessing element using key
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])


output :

{1: 'Code'}
Code
For


Removing Elements from Dictionary

Using del keyword

In Python Dictionary, deletion of a element perform by using the del keyword. Using del keyword, specific values from a dictionary as well as whole dictionary can be deleted. Items in a Nested dictionary can also be deleted by using del keyword and providing specific nested key and particular key to be deleted from that nested Dictionary.


# Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Code',
        'A' : {1 : 'Code', 2 : 'For', 3 : 'Job'},
        'B' : {1 : 'dudle', 2 : 'Life'}}
print("Initial Dictionary: ")
print(Dict)
  
# Deleting a Key value
del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)
  
# Deleting a Key from
# Nested Dictionary
del Dict['A'][2]
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)


output :

Initial Dictionary: 
{5: 'Welcome', 6: 'To', 7: 'Code', 'A': {1: 'Code', 2: 'For', 3: 'Job'}, 'B': {1: 'dudle', 2: 'Life'}}

Deleting a specific key: 
{5: 'Welcome', 7: 'Code', 'A': {1: 'Code', 2: 'For', 3: 'Job'}, 'B': {1: 'dudle', 2: 'Life'}}

Deleting a key from Nested Dictionary: 
{5: 'Welcome', 7: 'Code', 'A': {1: 'Code', 3: 'Job'}, 'B': {1: 'dudle', 2: 'Life'}}


Using pop() method

pop() method is used to return and delete the value of the key specified.

# Creating a Dictionary
Dict = {1: 'Code', 'name': 'For', 3: 'Job'}
  
# Deleting a key 
# using pop() method
pop_ele = Dict.pop(1)
print('\nDictionary after deletion: ' + str(Dict))
print('Value associated to poped key is: ' + str(pop_ele))



output :


Dictionary after deletion: {'name': 'For', 3: 'Job'}
Value associated to poped key is: Code


Using popitem() method

The popitem() returns and removes an arbitrary element (key, value) pair from the dictionary.

# Creating Dictionary
Dict = {1: 'Code', 'name': 'For', 3: 'Dudle'}
  
# Deleting an arbitrary key
# using popitem() function
pop_ele = Dict.popitem()
print("\nDictionary after deletion: " + str(Dict))
print("The arbitrary pair returned is: " + str(pop_ele))


output :

Dictionary after deletion: {1: 'Code', 'name': 'For'}
The arbitrary pair returned is: (3, 'Dudle')


Using clear() method

All the items from a dictionary can be deleted at once by using clear() method.

# Creating a Dictionary

Dict = {1: 'Code', 'name': 'For', 3: 'Dudle'}
  
  
# Deleting entire Dictionary
Dict.clear()
print("\nDeleting Entire Dictionary: ")
print(Dict)

output :

Deleting Entire Dictionary: 
{}



In this article i have describe about dictionary

Next Article : Array in Python Set 1

Recommended Post : Set in Python

                      Tuple in Python               

    Introduction to Data types




 #data science from scratch
 #micropython esp32
 #machine learning using python
 #matplotlib
 #python 3
 #scikit learn
 #tkinter
 #earn python the hard way
 #python for data analysis
 #python ai
 #fluent python
 #introduction to machine learning with python
 #python machine learning
 #deep learning with python
 #best way to learn python
 #fluent python
 #introduction to machine learning with python
 #python machine learning
 #deep learning with python







Post a Comment

6 Comments

If you have any doubt, Please let me know.