Python | Dictionary

Python Dictionary is an unordered collection of key:value pairs. Key need to be unique, immutable(string, number) and value can be anything doesn’t matter it’s unique, immutable or not.
For example – { 1 : “World”, 2 : “Life”} here 1, 2 are keys and strings “World”, “Life” are values of these keys respectively.

Ways to create Dictionary in Python

In Python Programming Language, Dictionary can be created using curly brackets or dict() function. Like { 1: “USA”, 2 : “Canada” } and dict({ 1: “USA”, 2 : “Canada”} ) are both same dictionaries but created using different syntax.

  • { key1:value1, key2:value2, ………….. } first method for creating dictionary
  • dict({ key1:value1, key2:value2, ………….. }) second method for creating dictionary

🤔 Note
How to create an empty dictionary in Python? Empty dictionary can be created in Python by using empty curly brackets or empty dict() function. Like both { } and dict() are empty dictionaries.

How to access elements of a dictionary in Python?

First Way
Values of keys inside a dictionary in Python can be accessed by putting name of key inside square brackets and putting this after name of dictionary.
For example – If there’s a dictionary x = { 1:”Python”, 2:”JavaScript” } then doing x[1] will return “Python”.

Second Way
Instead of using key name inside square brackets after name of dictionary, you can also use get() function by passing key name inside this function.
For example – Like for above mentioned dictionary x = { 1:Python”, 2:”JavaScript” } you can also do x.get(1) this will return “Python”.

Difference between two ways
If for first way you put some key inside square bracket which actually is not inside Dictionary then it will raise a KeyError but for second way using get() function it will return none.
So in order to not run into these errors, just make sure that whatever key’s value your trying to access does exist inside dictionary. Below I’ve explained how you can check whether some key exists inside dictionary or not?

Some other stuff about Python Dictionaries



Josh

Hi, I'm Josh a Computer Science graduate from California State University, Sacramento since coming out with my Master's from university. I've worked with multiple startups across US and in UK as well primarily as a Python Developer. Here on this website, I'm sharing my knowledge of Python. If you want to ask me anything about Python feel free to reach out, I would be happy to help you out.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts