Dictionary is very useful in Python Programming and gives a intuitive way to organize data in key value pairs. Phone Book is an example of Dictionary where Phone number can be mapped with Name of a Person.
In this Article we will discuss below points on Dictionary.
- What is Dictionary in Python ?
- How to create a Dictionary ?
- How to access elements of a Dictionary ?
- How to Print Dictionary Keys ?
- How to print dictionary keys and values using for loop ?
What is Dictionary?
Python Dictionaries are collection of key-value pairs and it’s represented in curly braces {} .
How to create a Dictionary?
To create a Dictionary we need to place elements in key:value pairs separated by comma within curly braces. Dictionary values can be of any data type and can be duplicated but the keys can’t be duplicated. The below example shows how to create a Dictionary.
<dictionary-name> = {<key1>:<value1>,<key2>:<value2>,<key3>:<value3>…………..}
Example:
capitals = {"India":"New Delhi", "Australia":"Canberra", "Chile":"Santiago","Fiji":"Suava"}
Here capitals is the name of dictionary that stores the name of the country as Keys and their capital as values of respective keys.
How to access elements of a Dictionary?
The elements in the Dictionary can be accessed through keys defined in key:value pairs as below.
<dictionary-name>[ <key> ]
So to access the value for key defined as “India” in above capitals dictionary, we can write
capitals[“India”] and it will give the output as New Delhi.
How to Print Dictionary Keys?
You can print all keys of a dictionary using print(capitals.keys()). It will give output as dict_keys([‘India’, ‘Australia’, ‘Chile’, ‘Fiji’])
To print specific key of a dictionary you need to specify the keyname with dictionary as below
print(capitals[“Australia”]) & It will give output as Canberra.
How to print dictionary keys and values using for loop ?
We can print dictionary keys and values using in operator. Let’s see an example.
Example
dict = {"A": 5, "B": 10, "C": 15, "D": 20}
for i in dict:
print(i, dict[i])
Output:
I hope you will like this post. Happy Blogging!