Welcome to this tutorial on How to Create a Python Dictionary, which is used to store multiple KEY:VALUE pairs into a single Python Variable.
Python Dictionaries are Ordered (as of Python 3.7), Mutable and do not allow for Duplicates. The easiest way to recognize a Python Dictionary is by its usage of Braces { }, as well as its [KEY:VALUE] pairs.
Dictionaries are one of 4 built-in data types in Python, that are used to store collections of data. The other 3 Python Iterables (Collection Data Types) are Lists, Tuples, and Sets, each with their own different qualities and usages.
NOTE: This tutorial requires that Python is already installed, as well as an IDE (Integrated Development Environment), such as PyCharm. It’s also recommended that you have a basic understanding of How to Use Python if this is your first time learning Python, as well as Python Variables and Data Types.
With that said, let’s get started with this free Python Dictionary tutorial.
How to Create a Dictionary in Python
A Python Dictionary is created using Braces { }, in which its KEY:VALUE pairs are stored. A Dictionary is assigned to a Variable name as follows:
Dictionary_Variable_Name = {Key0: Value0, Key1: Value1, Key2: Value2, Key3: Value3}
Python Dictionary Example:
Here is a Python Dictionary that contains three car brands and a model of a car in each brand. These elements are in the form of Python Strings for both the KEY (Brand) : VALUE (Model) configuration. This is contained and assigned to a Variable named “car_dictionary”:
car_dictionary = {"BMW": "M5", "Porsche": "Carrera", "Mercedes": "AMG GT"}
print(car_dictionary)
#>> {'BMW': 'M5', 'Porsche': 'Carrera', 'Mercedes': 'AMG GT'}
We then print out the “car_dictionary” by using the “print(car_dictionary)” statement, Python outputs {‘BMW’: ‘M5’, ‘Porsche’: ‘Carrera’, ‘Mercedes’: ‘AMG GT’}, which is our Dictionary of cars.
Braces { } are Required when creating a Python Dictionary
A Dictionary cannot be created without the use of Braces { }.
car_dictionary = "BMW": "M5", "Porsche": "Carrera", "Mercedes": "AMG GT"
print(car_dictionary)
#>> SyntaxError: invalid syntax
Trying to create a Dictionary without using { } will result in a Syntax Error message.
Python Dictionaries work with only a single Key:Value pair
A Python Dictionary can be created with only one Key: Value pair.
For example, if there is only one Key:Value pair in the Dictionary, such as “BMW”: “M5”, it remains a Dictionary. We can test this using the type() Function:
car_dictionary = {"BMW": "M5"}
print(car_dictionary)
print(type(car_dictionary)) # Calling the “car_dictionary” Variable inside type() Function
#>> {'BMW': 'M5'}
#>> <class 'dict'> # Confirmation that this is in fact a Dictionary
The “BMW”: “M5” are the only Key:Value pair in the Dictionary, yet Python still accepts it as a legitimate Dictionary, which we can see when using the type() Function.
Python Dictionaries don’t require any Key:Value pairs
Dictionaries in Python can be completely empty, requiring no KEY:VALUE pairs at all:
car_dictionary = {}
print(car_dictionary)
print(type(car_dictionary)) # Calling the “car_dictionary” Variable inside of the type() Function
#>> {}
#>> <class 'dict'> # Confirmation that this is in fact a Dictionary
Again, we see that this still remains a Dictionary, even with no values added to it.
Data Types that a Python Dictionary can contain
Python Dictionaries can contain any of the following Data Types as either KEYS or VALUES, mixed within a single Dictionary:
- Integers (int) – Whole numbers such as: 1, 14, 576.
- Floating Point (float) – Decimal values such as: 1.24, 5.6 and Fractional Values such as 1/2, 9/6.
- Strings (str) – Sequence of Characters such as: “I love Python”, “this course is great”, “year 3000”.
- Booleans (bool) – Logical values representing: TRUE or FALSE.
For example, we are able to create the following mixed Data Type Dictionary:
mixed_dictionary = {"The sky is blue": 1.3, 5: 25, True: "Hello"} #int, float, string, bool
print(mixed_dictionary)
#>> {'The sky is blue': 1.3, 5: 25, True: 'Hello'}
All four Data Types, including the int, float, string and bool were successfully output within the Dictionary, using them either as Keys or Values.
Python Iterables that can be stored within a Dictionary
Python Dictionaries aren’t limited to only storing single Data Types either, as they are able to store Python Iterables (Collection Data Types) as well.
Dictionaries are however limited to only being able to store Tuples as Keys or Values, due to a Tuple being Immutable, while Lists and Sets are Mutable and will thus not work inside of a Dictionary.
mixed_iterable_dict = {("apple", "orange", "grape"): 8} # tuple
print(mixed_iterable_dict)
#>> {('apple', 'orange'): 8}
Using the Print Statement to output the results, we can see that Python successfully accepted the Tuple Iterables as a Key within the Dictionary.
We can also assign the Tuples as Variables first, before using them as the Keys in the Dictionary.
fruit_tuple = ("apple", "orange", "grape")
meat_tuple = ("beef", "pork", "chicken")
food_dict = {fruit_tuple: 8, meat_tuple: 5}
print(food_dict)
{('apple', 'orange', 'grape'): 8, ('beef', 'pork', 'chicken'): 5}
How to Check for a Python Dictionary using the type() Function
If you are unsure if a variable or output is in fact a Dictionary, you can easily check this using the type() Function:
car_dictionary = {"BMW": "M5", "Porsche": "Carrera", "Mercedes": "AMG GT"}
print(car_dictionary)
print(type(car_dictionary)) # type() Function within Print Statement
#>> {'BMW': 'M5', 'Porsche': 'Carrera', 'Mercedes': 'AMG GT'}
#>> <class 'dict'> # Confirmation that this is a Dictionary
Python outputs <class ‘dict’>, which confirms to us that the Variable is indeed a Dictionary.
How to Check the Length of a Python Dictionary using len() Function
The length of a Python Dictionary can be defined using the len() Function:
car_dictionary = {"BMW": "M5", "Porsche": "Carrera", "Mercedes": "AMG GT"}
print(len(car_dictionary))
#>> 3
This outputs the number 3 (int), which tells us how many Key:Value pairs we have in our Python Dictionary.
Python Dictionaries are Ordered, Mutable & Do not Allow Duplicates
The Key:Value pairs in a Python Dictionary are, Ordered, Mutable and DO NOT allow for Duplicates.
Python Dictionaries are Ordered
Python Dictionaries are Ordered and thus the Key:Value pairs within a Dictionary have a defined order.
Being Ordered means that no matter how many times a Python Dictionary is output by Python (such as using a Print Statement), the order of the Key:Value pairs in the Dictionary will not change order:
# FIRST RUN
car_dictionary = {"BMW": "M5", "Porsche": "Carrera", "Mercedes": "AMG GT"}
print(car_dictionary)
#>> {'BMW': 'M5', 'Porsche': 'Carrera', 'Mercedes': 'AMG GT'}
# SECOND RUN
car_dictionary = {"BMW": "M5", "Porsche": "Carrera", "Mercedes": "AMG GT"}
print(car_dictionary)
#>> {'BMW': 'M5', 'Porsche': 'Carrera', 'Mercedes': 'AMG GT'}
# THIRD RUN
car_dictionary = {"BMW": "M5", "Porsche": "Carrera", "Mercedes": "AMG GT"}
print(car_dictionary)
#>> {'BMW': 'M5', 'Porsche': 'Carrera', 'Mercedes': 'AMG GT'}
Each output run will keep the KEY:VALUE pairs in the exact same defined order, as specified in the original Dictionary.
Python Dictionaries are Mutable
Python Dictionaries are Mutable, meaning that we can change, add and remove Key: Value pairs in a Dictionary, after it has been created, using the available List Methods:
Python Dictionary Methods
- clear() : Removes all the Key:Value pairs from the Dictionary
- copy() : Returns a copy of the dictionary
- fromkeys() : Returns a dictionary with the specified keys and value
- get() : Returns the value of the specified key
- items() : Returns a List containing a Tuple with each key value pair
- keys() : Returns a List containing the Dictionary’s Keys
- pop() : Removes the Key:Value pair with the specified key
- popitem() : Removes the last inserted Key:Value pair
- setdefault() : Returns the value of the specified Key. If the key does not exist: insert the key, with the specified value
- update() : Updates the Dictionary with the specified Key:Value pair
- values() : Returns a list of all the values in the dictionary
Python Dictionaries DO NOT Allow Duplicates
A Python Dictionary does not allow for duplicate KEY:VALUE pairs.
For example, if we try to add a KEY:VALUE pair that already exists in the original Dictionary, it won’t be added:
car_dictionary = {"BMW": "M5", "Porsche": "Carrera", "Mercedes": "AMG GT", "Landrover": "Discovery"}
car_dictionary["Landrover"] = "Discovery"
print(car_dictionary)
#>> {'BMW': 'M5', 'Porsche': 'Carrera', 'Mercedes': 'AMG GT', 'Landrover': 'Discovery'}
Similarly, if we try to add the same KEY:VALUE pair twice, it will only be added once.
car_dictionary = {"BMW": "M5", "Porsche": "Carrera", "Mercedes": "AMG GT"}
car_dictionary["Landrover"] = "Discovery"
car_dictionary["Landrover"] = "Discovery"
print(car_dictionary)
#>> {'BMW': 'M5', 'Porsche': 'Carrera', 'Mercedes': 'AMG GT', 'Landrover': 'Discovery'}
Python Dictionary Conclusion
I hope you enjoyed this tutorial on how to create a Python Dictionary. This should give you the starting knowledge you need to easily create Dictionaries in Python for your code or project.
Python Dictionary Summary
Here is a summary of what we learnt when creating a Python Dictionary:
- Python Dictionaries require Braces { }.
- Python Dictionaries can be created using a single Key:Value pair.
- Python Dictionaries can be empty with no Key:Value pairs at all.
- Python Dictionaries can contain Integer (int), Floating Point (float), Strings (str) and Booleans (bool) Data Types as their Keys or Values.
- Python Dictionaries can only contain one other Python Iterables, which is a Tuples as a Key or Value.
- The type() Function can be used to check if a Variable is a Dictionary.
- The len() Function can be used to check the Length of a Dictionary.
- Python Dictionaries are Ordered, meaning that the Key:Value pairs will always have a defined order that will not change.
- Python Dictionaries are Mutable, meaning that Key:Value pairscan be changed, added, removed, sorted, reversed using Methods.
- Python Dictionaries do not allow for Duplicate Key:Value pairs, meaning that it is not possible to have two or more of the same pair in a Dictionary.
Remember, that when choosing a the Python Iterables (List, Tuple, Set or Dictionary) for your code, it is very important to choose the correct one for the required use case, as each of the Python Iterables has it own qualities and properties, which have a direct influence on both performance and security of your code.
Full Python Beginners Course
This tutorial is just a small sample of the my Full Python Beginners Course. The entire course is recorded and available in High Definition video, allowing you to easily learn Python as you watch and follow along. If you have been wanting to start learning Python, but haven’t been sure where to start, then this is the course for you, so don’t to miss out!
Share the love
If you enjoyed this tutorial content and would like others to benefit from it as well, make sure to share it on your favorite Social Media platform, using the share buttons below.
Subscribe for News & Discount Offers
Subscribe right now to gain instant access to the latest news and tutorials while also being the first to know about, exclusive offers and discounts!