Python Dictionaries
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.
Example
Create and print a dictionary:
thisdict = {
"apple": "green",
"banana": "yellow",
"cherry": "red"
}
print(thisdict)
Run example »
Example
Change the apple color to "red":
thisdict = {
"apple": "green",
"banana": "yellow",
"cherry": "red"
}
thisdict["apple"] = "red"
print(thisdict)
Run example »
The dict() Constructor
It is also possible to use the dict() constructor to make a dictionary:
Example
thisdict = dict(apple="green", banana="yellow", cherry="red")
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
Run example »
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = dict(apple="green", banana="yellow", cherry="red")
thisdict["damson"] = "purple"
print(thisdict)
Run example »
Removing Items
Removing a dictionary item must be done using the del()
function in python:
Example
thisdict = dict(apple="green", banana="yellow", cherry="red")
del(thisdict["banana"])
print(thisdict)
Run example »
Get the Length of a Dictionary
The len()
function returns the size of the dictionary:
Example
thisdict = dict(apple="green", banana="yellow", cherry="red")
print(len(thisdict))
Run example »