Dictionary Data Type in Python

Rina Mondal
4 min readJan 31, 2024

--

Dictionary is a built in data type in Python mainly used for mapping purpose. In a dictionary, each key must be unique and is associated with a corresponding value. The combination of a key and its associated value is referred to as a “key-value pair." Let’s dive deep.

Creation of a Dictionary:

Dictionary can be created in many ways. Dictionaries are defined using curly braces {} and a colon : to separate keys and values.

#Creating a dictionary in various ways

# empty dictionary
d = {}
print(d)
#Output: {}



# 1D dictionary
d1 = { 'name' : 'john' ,'gender' : 'male' }
print(d1)
#Output: {'name':'john','gender':'male'}




# with mixed keys
d2 = {(1,2,3):1,'hello':'world'}
print(d2)
#Output: {(1,2,3):1,'hello':'world'}



# 2D dictionary
s = {
'name':'john',
'college':'calcutta university',
'sem':4,
'subjects':{
'dsa':50,
'maths':67,
'english':34
}
}
print(s)

#Output:
{'name': 'john',
'college': 'calcutta university',
'semester': 4,
'subjects': {'dsa': 50, 'maths': 67, 'english': 34}



# using sequence and dict function
d4 = dict([('name','john'),('age',32),(3,3)])
print(d4)
#Output: {'name':'john','age':32,3:3}



# duplicate keys
d5 = {'name':'john','name':'rahul'}
print(d5)
#Output: {'name':'rahul'} #dictionary keys must be unique
#but if we try to create, it will keep the last key-value




# mutable items as keys
d6 = {'name':'john',(1,2,3):2}
print(d6)
#Output: {'name':'john',(1,2,3):2}

Accessing items:

If you want to access specific items from the nested dictionary, you can use square brackets [] to navigate through the keys.

my_dict = {'name': 'Jack', 'age': 26}
my_dict['age']
#Output: 26


# also access age by get keyword
my_dict.get('age')
# Output: 26

Adding key-value pair:

To add a new key-value pair to the dictionary , you can simply use the square bracket notation to assign a value to a new key.

d4 = dict([('name','john'),('age',32),(3,3)])
d4['gender'] = 'male'
print(d4)

#Output - {'name':'john','age':32,3:3,'gender':'male'}
#Adding key-value pair in 2D dictionary
s = {
'name':'john',
'college':'calcutta university',
'sem':4,
'subjects':{
'dsa':50,
'maths':67,
'english':34
}
}
s['subjects']['ds'] = 75
print(s)

#Output
{'name': 'john',
'college': 'calcutta university',
'sem': 4,
'subjects': {'dsa': 50, 'maths': 67, 'english': 34, 'ds': 75}}

Remove key-value pair:

pop() method: To remove a specific key-value pair.

popitem() method : To remove and return the last key-value pair.

del method: To delete a specific key and its corresponding value, or it can also delete the entire dictionary.

clear() method: used to remove all items from a dictionary, leaving it empty. It does not delete the dictionary itself, it just removes all key-value pairs.

d={'name':'john', 'age':32,'gender':'male', 'weight':72}
# pop
d.pop('age')
print(d)

#Output
{'name':'john', 'gender':'male', 'weight':72}

# popitem
d.popitem()
print(d)

#Output
{'name':'john', 'age':32, 3:3, 'gender':'male'}

# del
del d['name']
print(d)

#Output
{'age':32, 3:3, 'gender':'male', 'weight':72}

# clear
d.clear()
print(d)

#Output
{}

#Remove key-value pair in 2D dictionary
s = {
'name':'john',
'college':'calcutta university',
'sem':4,
'subjects':{
'dsa':50,
'maths':67,
'english':34
}
}
del s['subjects']['maths']
print(s)

#Output
{'name': 'john',
'college': 'calcutta university',
'sem': 4,
'subjects': {'dsa': 50, 'english': 34, 'ds': 75}}

Editing key-value pair: To edit a key-value pair in a dictionary, you can simply assign a new value to the desired key.

s = {
'name':'john',
'college':'calcutta university',
'sem':4,
'subjects':{
'dsa':50,
'maths':67,
'english':34
}
}
s['subjects']['dsa'] = 80
print(s)

#Output
{'name': 'john',
'college': 'calcutta university',
'sem': 4,
'subjects': {'dsa': 80, 'english': 34, 'ds': 75}}

Dictionary Operations:

Membership: In Python, you can use the in and not in operators to check for membership in a dictionary. These operators check whether a specified key is present in the dictionary.

s = {
'name':'john',
'college':'calcutta university',
'sem':4,
'subjects':{
'dsa':50,
'maths':67,
'english':34
}
}
print('name' in s)

#Output
True

Iteration: You can iterate over the keys, values, or key-value pairs.

d = {'name':'john','gender':'male','age':33}
for i in d:
print(i)

#Output
name
gender
age



for i in d:
print(i,d[i])

#Output
name john
gender male
age 33

Dictionary Functions:

len/max/min/sorted can be performed on dictionary data types.

#len/min/max/sorted
d = {'name':'john','gender':'male','age':33}
len(d)
#Output: 3


min(d)
#Output: age


max(d)
#Output: name

sorted(d) #sorts the keys of the dictionary d alphabetically
#Output: ['age', 'gender', 'name']
# To fetch items/keys/values
d = {'name':'john','gender':'male','age':33}
print(d.items())
print(d.keys())
print(d.values())

#Output
dict_items([('name', 'john'), ('gender', 'male'), ('age', 33)])
dict_keys(['name', 'gender', 'age'])
dict_values(['john', 'male', 33])



#update a dictionary
d1 = {1:2,3:4,4:5}
d2 = {4:7,6:8}

d1.update(d2)
#Output
{1: 2, 3: 4, 4: 7, 6: 8}

Characteristics:

  1. Mutable: Dictionaries are mutable, meaning you can add, modify, or remove key-value pairs after the dictionary is created. We have seen examples above.
  2. Unique Key-Value Pairs: Each element in a dictionary consists of a key-value pair. The key is used to access its associated value. Keys must be unique within a dictionary.
  3. Flexible Key Types: Keys can be of any immutable data type (strings, numbers, or tuples containing only immutable elements). Values can be of any data type, including other dictionaries.

Dictionary Comprehension:

Dictionary comprehension is a concise way to create dictionaries in Python using a single line of code. It follows a similar syntax to list comprehension but results in a dictionary.

# The general syntax for dictionary comprehension is:
{key_expression: value_expression for item in iterable}
#print 1st 10 numbers and their squares
{i:i**2 for i in range(1,11)}

#Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

Explore Data Science Roadmap.

Explore my YouTube channel where I explain Data Science related topics for free.

If you found this guide helpful , why not show some love?

Give it a Clap 👏, and if you have questions or topics you’d like to explore further, drop a comment 💬 below 👇

--

--

Rina Mondal

I have an 8 years of experience and I always enjoyed writing articles. If you appreciate my hard work, please follow me, then only I can continue my passion.