A dictionary is a collection of unordered, modifiable (mutable), paired (key: value) data types.
To create a dictionary, we use curly brackets, {} or the dict() built-in function.
# syntax
empty_dict = {}
# Dictionary with data values
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
Example:
person = {
'first_name':'Tech',
'last_name':'G',
'age':25,
'country':'India',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'110034'
}
}
The dictionary above shows that a value could be any data type: string, boolean, list, tuple, set, or dictionary.
It checks the number of ‘key: value’ pairs in the dictionary.
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print(len(dct)) # 4
Example:
person = {
'first_name':'Tech',
'last_name':'G',
'age':25,
'country':'India',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'110034'
}
}
print(len(person)) # 7
We can access Dictionary items by referring to their key name.
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print(dct['key1']) # value1
print(dct['key4']) # value4
Example:
person = {
'first_name':'Tech',
'last_name':'G',
'age':25,
'country':'India',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'110034'
}
}
print(person['first_name']) # Tech
print(person['country']) # India
print(person['skills']) # ['JavaScript', 'React', 'Node', 'MongoDB', 'Python']
print(person['skills'][0]) # JavaScript
print(person['address']['street']) # Space street
print(person['city']) # Error
Accessing an item by key name raises an error if the key does not exist. To avoid this error first, we have to check if a key exists or if we can use the get method. The get method returns None, which is a NoneType object data type if the key does not exist.
person = {
'first_name':'Tech',
'last_name':'G',
'age':25,
'country':'India',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'110034'
}
}
print(person.get('first_name')) # Tech
print(person.get('country')) # India
print(person.get('skills')) #['HTML','CSS','JavaScript', 'React', 'Node', 'MongoDB', 'Python']
print(person.get('city')) # None
We can add new key and value pairs to a dictionary
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct['key5'] = 'value5'
Example:
person = {
'first_name':'Tech',
'last_name':'G',
'age':25,
'country':'India',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'110034'
}
}
person['job_title'] = 'Instructor'
person['skills'].append('HTML')
print(person)
We can modify items in a dictionary
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct['key1'] = 'value-one'
Example:
person = {
'first_name':'Tech',
'last_name':'G',
'age':25,
'country':'India',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'110034'
}
}
person['first_name'] = 'Pravin'
person['age'] = 25
We use the in operator to check if a key exists in a dictionary
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print('key2' in dct) # True
print('key5' in dct) # False
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct.pop('key1') # removes key1 item
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct.popitem() # removes the last item
del dct['key2'] # removes key2 item
Example:
person = {
'first_name':'Tech',
'last_name':'G',
'age':25,
'country':'India',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'110034'
}
}
person.pop('first_name') # Removes the firstname item
person.popitem() # Removes the address item
del person['is_married'] # Removes the is_married item
The items() method changes the dictionary to a list of tuples.
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print(dct.items()) # dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3'), ('key4', 'value4')])
If we don’t want the items in a dictionary we can clear them using clear() method
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print(dct.clear()) # None
If we do not use the dictionary we can delete it completely
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
del dct
We can copy a dictionary using a copy() method. Using copy we can avoid mutation of the original dictionary.
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct_copy = dct.copy() # {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
The keys() method gives us all the keys of a dictionary as a list.
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
keys = dct.keys()
print(keys) # dict_keys(['key1', 'key2', 'key3', 'key4'])
The values method gives us all the values of a dictionary as a list.
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
values = dct.values()
print(values) # dict_values(['value1', 'value2', 'value3', 'value4'])
Now do some exercises for your brain and muscles.
Day 30 Conclusions In the process of preparing this material, I have learned quite a…
Day 29: Building API In this section, we will cover a RESTful API that uses HTTP…
Day 28: Application Programming Interface (API) API API stands for Application Programming Interface. The kind…
Day 27: Python with MongoDB Python is a backend technology, and it can be connected…
Day 26: Python for Web Python is a general-purpose programming language, and it can be…
Day 25: Pandas Pandas is an open-source, high-performance, easy-to-use data structure, and data analysis tool…
View Comments