Dictionaries
Dictionaries are a way of bundling information together in one variable.
# This is a dictionary!
me = { "name": "Soma", "city": "Brooklyn", "age": 107 }
# In order to get things out you use me["name"]
print(me["name"]) # outputs: Soma
print(me["city"]) # outputs: Brooklyn
The data in a dictionary is structured in comma-separated key-value pairs.
{ 'key': 'value', 'key2': 'value2'}
When you see curly braces, { }
, you’ll know that you’re dealing with a dictionary.
Details on keys
The key-value pairs in a dictionary are not ordered, meaning that each time you print(me)
, you may see name
, city
, and age
appear in different orders.
# You can only get data out of a dictionary by using the key
city = { 'name': 'Los Angeles', 'state': 'California', 'population': 3.884 }
# 'name' is a key
# 'Los Angeles' is a value
print(city['name'])
# 'state' is a key
# 'California' is a value
print(city['state'])
# 'population' is a key
# 3.884 is a value
print(city['population'])
You can also use dictionaries the same way you would use normal variables in a sentence. You need to be careful, though, as you’re suddenly using a lot of different punctuation characters on the same line and it’s easy to get your '
and [
and )
all mixed up.
city = {
'name': 'Los Angeles',
'state': 'California',
'population': 3.884
}
print("The city of", city['name'], "in the state of", city['state'], "has a population of", city['population'], "million people")
There’s an easier way to fill in the blanks, but we won’t talk about that for a while. You can look at the example that uses **coord
if you’re curious, though!
Working with dictionaries
There are two common situations in which a dictionary is useful.
1. Storing multiple attributes of one thing
# Lots of info about Los Angeles
city = { 'name': 'Los Angeles', 'state': 'California', 'population': 3.884 }
2. Storing the same attribute of many things
# A handful of states
state_populations = {
'California': 38.8,
'Virginia': 8.326,
'New Hampshire': 1.327
}
As you can see from the example above, you can also split your definitions across multiple lines if you’d like. Just make sure you don’t forget the ,
at the end of each line.
If you’re exploring unfamiliar data, you should usually look at the keys with .keys()
and then explore inside of each key.
Functions and methods
To read about functions and methods that are useful for dictionaries, scroll down on the functions and methods page.