A dictionary holds data as key:value pairs.
This kind of collection keeps its order, can be changed, and refuses duplicates.
You write one with curly brackets, listing its keys and values inside:
Example
Build a dictionary and print it:
Output: complete Python program
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Items in a dictionary keep their order, can be modified, and cannot be duplicated.
Each item is a key:value pair, and the key's name is how you get to it.
Example
Print the value stored under "brand":
Output: complete Python program
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ordered or Unordered?
An ordered dictionary has a fixed sequence of items that stays the same.
An unordered collection has no defined sequence, so you cannot point to an item by its index.
Note: Dictionaries have been ordered since Python version 3.7. Up to and including Python 3.6, they were unordered.
Changeable
A dictionary stays open to edits after you create it: items can be changed, added or removed.
Duplicates Not Allowed
Each key can appear only once in a dictionary:
Example
Repeating a key overwrites the earlier value:
Output: complete Python program
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Dictionary Length
Call the len() function to find out how many items a dictionary holds:
Example
Count the dictionary's items and print the total:
Output: complete Python program
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(len(thisdict))
Dictionary Items - Data Types
A dictionary value can have any data type you like:
Example
Values that are a string, a boolean, an int and a list:
Output: complete Python program
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(thisdict)
type()
Python treats every dictionary as an object whose data type is 'dict':
Example
Ask Python for the type of a dictionary:
Output: complete Python program
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
The dict() Constructor
You can also build a dictionary by calling the dict() constructor.
Example
Build a dictionary with the dict() constructor:
Output: complete Python program
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)