-
Data Structures
-
Iteration
-
Mathematics
-
Files
-
Programming On A Machine
-
Exercises
Dictionary Structure
A dictionary
is a collection of items.
Each item in the collection has a key
and a value
We use the key
to set and get the value
.
First we create a dictionary with the keys and values. This example will be a dictionary of names to ages
ages = {
'bob': 54,
'alice': 36,
'carl': 21
}
In the example you can see each name is a key, and the key is a type string
.
The key has a value specified with the colon symbol :
So the format is 'key': value
.
We use a comma to seperate the items.
To get a value from a dictionary, we use the name of the dictionary and the key
ages = {
'bob': 54,
'alice': 36,
'carl': 21
}
value = ages['alice']
print(value)
value = ages['carl']
print(value)
We can also change the value for a key
in a dictionary using the assignment operator =
Why do we want a dictionary?
Since we can use the key
to get and set a value, we only need one variable to do this, the name of the dictionary.
Otherwise we would need a variable for each key. A dictionary can store thousands of keys, which is much better than thousands of variables.
Also, variable names are set in code and can't change. With a dictionary, you can add a new item and value using the assingment operator.
A disctionary is an easy way to store values while the program is running and you don't know how many values you will need.