DAY 11: Python Dictionary

In the last few lessons, we have learned about some Python constructs like lists, sets and tuples. In this thread, we will have a word about Python dictionary which is another type of data structure in Python. https://twitter.com/RealSaintSteven/status/1246019650569338882
What is Dictionary?
A real-life dictionary holds words and their meanings.
A dictionary is a collection which is unordered, changeable and indexed. A Python dictionary holds key-value pairs, and they are written with curly brackets, and they have keys and values.
Dictionary Syntax:

{ Key : Value }
{'brand': 'Honda', 'model': 'Accord', 'year': 2018}

a. Creating Dictionary
Creating a Python Dictionary is easy as pie. Separate keys from values with a colon(:), and a pair from another by a comma(,). Finally, put it all in curly braces.
* It isn’t necessary to use the same kind of keys (or values) for a dictionary in Python.
e.g dict={1:'carrots','two':[1,2,3]}

*You can also create a Python dict using comprehension.
e.g: thisdict ={ x*x:x for x in range(8)}
print(thisdict)
* You can declare one key more than once
e.g : mydict={1:2,1:3,1:4,2:4}
OUTPUT: {1: 4, 2: 4}
* You declare an empty dictionary and add elements later
animals={}

b. Accessing Python Dictionary
* To get the entire dictionary at once, type its name in the shell. eg print(thisdict)
c. Change Values
You can change the value of a specific item by referring to its key name:
thisdict ={"brand": "Honda", "model": "Accord", "year": 2010 }
thisdict["year"] = 2020
print(thisdict)
d. Deleting Dictionary
Unlike a tuple, a Python dictionary is mutable. So you can also delete a part of it

To delete the whole Python dict, simply use its name after the keyword ‘del’

To delete just one key-value pair, use the keyword ‘del’ with the key of the pair to delete
Just like List and Tuple, Dictionary also have Built-in Functions and Method.
I will advice you read about it as you will need always need it in your projects.
In this thread, we took a look at Python Dictionary.
We look at how to create, access, reassign, and delete a dictionary or its elements.

If you have a confusion? feel free to send DM!
You can follow @RealSaintSteven.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: