A dictionary or
dict
is a data type in Python that contains an unorganized collection of data in a key-value pair. So dictionaries are a data structure that stores data in a specific format. In my mental model, I compared it with the JavaScript
object
where we store data in key-value pairs. The keys of
dict
are represented by strings and the values can hold any data types. The values can be accessed using the corresponding keys. Since dictionaries don’t have any order, they are scattered around in the memory, unlike lists where they are stored in order in memory.
- user = {'name': 'Max', 'age': 40, 'married': False}
- print(user['name'])
- print(user['married']
Dictionary Keys
I mentioned that keys in a dictionary need to be of string
data type. Well, that is not entirely true. dict
keys can be of any immutable data type. Also, keys need to be unique. If a dictionary has more than one identical key, then the values are overridden. This is also termed as collision.
- abstract = { 'first': 123, True: 'hello', 777: [1,3,4,5]
- } print(abstract['first']
- print(abstract[True])
- print(abstract[777])
- }
- print(sample['username'])
Dictionary Methods
Checking for errors is a good programming practice because errors can break the program execution. In the context of a dictionary, if we try to access a key that does not exist, Python will throw an error and stop the program execution. This is not what we usually want so there is a built-in dictionary method to handle this.
- house = { 'rooms' : 4, 'occupants': 2, 'doors': 6
- }
- print(house['windows'])
-
- print(house.get('windows'))
- print(house.get('windows', 5))
There are some other ways to check if a specific key or value exists in a dictionary.
- user = {'name': 'Raghav', 'age': 20, 'country': 'India'}
- print('name' in user.keys())
- print('gender' in user.keys())
- print('Raghav' in user.values())
Some other useful dictionary methods are copy, clear, pop, update.
- cat = { 'name': 'Tom', 'greet': 'meow', 'health': 100
- }
- cat_copy = cat.copy()
- print(cat_copy)
- print(cat)
- print(cat)
- print(cat_copy)
- cat_copy.update({'color': 'Black'})
- print(cat_copy)
Tuples
Tuple data type is very similar to lists but they are immutable which means their value cannot be modified nor they can be sorted like lists.
- my_tuple = (1,2,3)
- print(my_tuple[1])
- print(1 in my_tuple)
Since tuples are immutable, they can be used as keys in dictionaries as well.
Actions on tuples
Just like lists, we can slice tuples because slicing returns a new copy and does not change the original data.
- colors = ('red', 'orange', 'blue', 'yellow')
- new_colors = colors[1:4]
- print(new_colors)
- print(color_1)
- print(others)
- print(colors.count('red'))
- print(colors.index('orange'))
Sets
Finally the last of data types 😋 (unless something new pops up in the journey).
Sets are a data structure that stores an unordered collection of unique objects. From my JavaScript universe, I can recollect there is a Set data structure there as well so it fits my mental model.
- set_of_numbers = {1,2,3,4,5,5}
- print(set_of_numbers)
This can be very helpful to remove, say, duplicate email addresses from a list of emails.
Actions on sets
The built-in methods of sets perform actions that are exactly similar to what we learnt in Venn Diagrams in primary math class. Here are some of them. I don’t find any need to memorize them because Set is the important thing to remember. The methods can be Googled anytime.
- set_a = {1,2,3,4,5}
- set_b = {4,5,6,7,8}
- print(set_a.union(set_b))
- print(set_a | set_b)
- print(set_a & set_b)
- print(set_a)
Oh boy! We are finally done with the data for the basic building blocks of Python with a basic understanding of its data types.
Tomorrow the focus will be to learn the conditional flow and iterations or looping in Python. I am pumped up now. Hope you have enjoyed following along as well.
Have a nice one!