Namaste Coders!
In this article, we will discuss dictionaries in Python.
What is Dictionary?
Dictionary is defined in key and value format {key : value}. In Dictionary each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}. Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
# dictionary in python
d1={}
print(type(d1)) #<class 'dict'>
d2=dict()
print(type(d2)) # <class 'dict'>
Properties
- Keys must be immutable datatypes that means you can use strings, numbers or tuples as dictionary keys.
- More than one entry per key not allowed. Which means no duplicate key is allowed.When duplicate keys encountered during assignment, the last assignment wins.
Accessing value
In dictionary we use keys to access that particular value as shown.
student={"name": "rahul","age":20,"gender":"male"}
# to access each element we use key
print("name of student is: ",student["name"])
print("age of student is: ",student["age"])
Output
name of student is: rahul
age of student is: 20
if key is not present than key error occurs as shown below:
student={"name": "rahul","age":20,"gender":"male"}
# to access each element we use key
print("name of student is: ",student["name"])
print("age of student is: ",student["age"])
print("email of student is: ",student["email"])
Output
name of student is: rahul
age of student is: 20
Traceback (most recent call last): File "c:/Users/meenu garg/Desktop/Python/PythonCodes/datatype/dictionary.py", line 13, in print("email of student is: ",student["email"]) KeyError: 'email'
Updating Dictionary
We can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example:
student={"name": "rahul","age":20,"gender":"male"}
# updating email
student['email']="rahul@gmail.com"
# to access each element we use key
print("name of student is: ",student["name"])
print("age of student is: ",student["age"])
print("email of student is: ",student["email"])
Output
name of student is: rahul
age of student is: 20
email of student is: rahul@gmail.com
Accessing Keys
stu = {
'name' :"John Doe",
'age' :15,
'courses': ['Python','Django']
}
print(stu.keys())
Output
dict_keys(['name', 'age', 'courses'])
Accessing Values
stu = {
'name' :"John Doe",
'age' :15,
'courses': ['Python','Django']
}
print(stu.values())
Output
dict_values(['John Doe', 15, ['Python', 'Django']])
Accessing Items
stu = {
'name' :"John Doe",
'age' :15,
'courses': ['Python','Django']
}
print(stu.items())
Output
dict_items([('name', 'John Doe'), ('age', 15), ('courses', ['Python', 'Django'])])
Iterating the dictionary
stu = {
'name' :"John Doe",
'age' :15,
'courses': ['Python','Django']
}
for k, v in stu.items():
print(f'key is {k} ---> value is {v}')
Output
key is name ---> value is John Doe
key is age ---> value is 15
key is courses ---> value is ['Python', 'Django']
get method
dictionary_name.get(key_name)
dictionary_name.get(key_name , return_statement)
get(key_name) method fetches value against a key. If key is not present then it returns None, also we could provide a custom return statement.
stu = {
'name' :"John Doe",
'age' :15,
'courses': ['Python','Django']
}
print(stu.get('age'))
print(stu.get('gender'))
print(stu.get('gender' , 'it is not present')
Output
15
None
it is not present
pop method
It pops out the key, value by passing key name as parameter.
Syntax
dictionary_name.pop(key_name)
Example
stu = {
'name' :"John Doe",
'age' :15,
'courses': ['Python','Django']
}
print("BEFORE: ",stu)
stu.pop('age')
print("AFTER: ",stu)
Output BEFORE: {'name': 'John Doe', 'age': 15, 'courses': ['Python', 'Django']}
AFTER: {'name': 'John Doe', 'courses': ['Python', 'Django']}
popitem method
popitem method pops out last element from the dictionary.
Syntax
dictionary_name.popitem()
Example
stu = {
'name' :"John Doe",
'age' :15,
'courses': ['Python','Django']
}
print("BEFORE: ",stu)
stu.popitem()
print("AFTER: ",stu)
Output
BEFORE: {'name': 'John Doe', 'age': 15, 'courses': ['Python', 'Django']}
AFTER: {'name': 'John Doe', 'age': 15}
Deleting Elements
We can also use del keyword to delete a particular key
Syntax
del dictionary_name[key]
stu = {
'name' :"John Doe",
'age' :15,
'courses': ['Python','Django']
}
del stu["age"]
print(stu["age"])
Output
Traceback (most recent call last): File "c:/Users/meenu garg/Desktop/Python/PythonCodes/datatype/dictionary.py", line 21, in print(student["age"]) KeyError: 'age'
Clearing out complete dictionary
Syntax
dictionary_name.clear()
stu = {
'name' :"John Doe",
'age' :15,
'courses': ['Python','Django']
}
stu.clear()
print(student)
Output
{}
The End
I hope you enjoyed the article and had a good learning experience.
Follow for more articles and keep sharing👩
Keep coding