Introduction to Dictionary
A dictionary in python is a collection of key:value pairs.
Curly brackets “{}” are used for the construction of the dictionary. The key and its value are separated by the colon(:) and each pair is separated by the comma.
A key in a dictionary can be any immutable data type only, for example, integer, string, or tuple. A value in a dictionary can be any data type, mutable or immutable, for example, integer, string, list, set, tuple, or dictionary itself.
In dictionaries, values can be accessed by using the keys instead of indexes.
dict = {'key1':'value1','key2':'value2'}
print(dict)
Value in the dictionary can be of any data type.
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
Accessing value with the key.
print(emp_details['first_name'])
print(emp_details['bill'])
Key can be any immutable data type. Dictionary with key as integer, string, and tuple.
numbers= {1:'One', 2:'Two', 'Three':'Three', ('Four','Five'):['Four','Five']}
Accessing the values.
print(numbers[1])
print(numbers[('Four','Five')])
Returns error on creating a dictionary using the list as a key.
numbers= {[1,2]:['One','Two']}
Characteristics of a Dictionary
Let us look at the characteristics of the dictionary one by one:
Characteristic | Meaning |
---|---|
Mutable | This means that we can change, add and remove the items stored within the dictionary. |
Unique | The keys in the dictionary cannot be duplicated. |
Ordered | From Python 3.7 and higher versions, dictionaries are ordered. |
Dictionaries are Ordered now
Dictionaries are ordered from python version 3.7, and before that dictionaries used to be unordered.
Changeable
Dictionaries are changeable, means we can change, add or remove items in the dictionary any time.
Dealing with duplicates
The Python Dictionary does not allow having two or more items with the same key. If we try to create a dictionary with more than one item having the same key, then it will keep only one and all others will get discarded.
The key ‘first_name’ is repeated twice in the below dictionary. It keeps only the latest one.
emp_details = {'first_name':'Tim',
'last_name':'Smith',
'first_name':'Rocky'}
emp_details
Dictionary keys are Special
Dictionary keys are special because of these properties:
1. Unique: The key of the dictionary cannot be repeated. In case we repeat the key, the old value of that key will be replaced by the new value.
In the below example, the key “1” is replaced with the value “Three”.
numbers= {1:'One', 2:'Two', 1:'Three'}
print(numbers)
2. Only mutable elements: The key in the dictionary can have only mutable elements like number, string list. Immutable elements like the list or the dictionary itself are not allowed as the key.
Number, string and tuple as the key.
numbers= {1:"One", "TWO":"Two", ("Three", "Four"):["Three", "Four"]}
print(numbers)
List as key result in error.
numbers= {["Three", "Four"]:["Three", "Four"]}
print(numbers)
Dictionary as key result in error.
numbers= {{"Three": "Four"}:["Three", "Four"]}
print(numbers)
Nested Dictionary
A nested dictionary means when we have a dictionary inside another dictionary. We can have multiple levels of dictionaries inside the dictionaries.
Ways to create Nested Dictionary
1. Directly nesting a new level inside the existing level.
nested_dictionary = {
"Bill" : {
"age" : 55,
"gender" : "Male"
},
"Steve" : {
"age" : 57,
"gender" : "Male"
},
"Lisa" : {
"age" : 52,
"gender" : "Female"
}
}
print(nested_dictionary)
2. Create single level dictionaries and then create a parent dictionary that contains single level dictionaries.
Bill = {
"age" : 55,
"gender" : "Male"}
Steve = {
"age" : 57,
"gender" : "Male"}
Lisa = {
"age" : 52,
"gender" : "Female"
}
nested_dictionary = {
"Bill" : Bill,
"Steve" : Steve,
"Lisa" : Lisa
}
print(nested_dictionary)
Access items of Nested Dictionary
To access the inner child. We first need to access the parent and keep on moving level by level.
employee_details = {
"Bill" : {
"age" : 55,
"gender" : "Male"
},
"Steve" : {
"age" : 57,
"gender" : "Male"
},
"Lisa" : {
"age" : 52,
"gender" : "Female"
}
}
print(employee_details["Bill"]["age"])
print(employee_details["Lisa"]["age"])
print(employee_details["Steve"])
Sort Dictionary
Python has the in-built function sorter() to sort the elements of the dictionary. It returns us a sorted list of keys in case we pass keys as argument and a sorted list of values in case we pass dict.values() as argument. In case, the argument is dict.items(), then it returns a list with tuples of key and value.
numbers= {1:'One', 5:'Five', 8:'Eight'}
print(numbers)
Sorting as per key.
print(sorted(numbers))
Sorting as per value.
print(sorted(numbers.items()))
Sorting as per key.
print(sorted(numbers.values()))
The type()
function
At any stage in our program, we may need to check whether the variable is a dictionary or not, we can use the type()
function for this purpose. If the type of the variable is a dictionary, then the type() function will return the ‘dict’ keyword.
emp_details = {'first_name':'Tim', 'last_name':'Smith', 'emp_id':200, 'programming_languages':['Python','C++','Java']}
print(type(emp_details))
The dict() Constructor
A dictionary can also be created using the dict() constructor. Here we have to pass the comma separated key-value pair in the pattern “key = value”.
emp_details = dict(first_name = 'Tim', last_name = 'Cook', emp_id = 200, bill = 200.20)
print(emp_details)
print(type(emp_details))
Dictionary Length
The len() function can be used to determine how many items we have in the dictionary.
numbers= {1:"One", 2:"Two", 3:"Three"}
print(len(numbers))
Membership Test
Membership operators in and not in are used to check whether a key is present in the dictionary or not. Note: This can be used to check the key only, not the values in the dictionary.
numbers= {1:"One", 2:"Two", 3:"Three"}
print(1 in numbers)
print(2 not in numbers)
Resources
These are the Free Notes shared with the YouTube Video.
**Note: All links are Password Protected. For the PASSWORD, please follow the steps in the DESCRIPTION of the respective Video.
Chapter 7 - Dictionary
Linked video : https://youtu.be/inCl3paBc1U