In this Article we will discuss as below.

  • What is Dictionary in Python.
  • How to create a Dictionary.
  • How to access elements of a Dictionary.
  • How to Print Dictionary Keys.

What is Dictionary?

Python Dictionaries are collection of key-value pairs and it’s represented in curlybraces {} .

How to create a Dictionary?

To create a Dictionary , we need to include key:value pairs in curly braces as below
<dictionary-name> = {<key1>:<value1>,<key2>:<value2>,<key3>:<value3>…………..}
Example:
capitals = {“India”:”New Delhi”, “Australia”:”Canberra”, “Chile”:”Santiago”,”Fiji”:”Suava”}
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?

In Dictionary, the elements 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 need to write
capitals[“India”]
and it will give output as New Delhi.

How to Print Dictionary Keys
?

You can print all keys of a dictionary as
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.


I hope you will like this post. Happy Blogging!