Skip to main content

Dictionaries

Dictionaries are likely the most used data type.  These store data in "key, value" pairs and like other data types, nested values of other types are also allowed.

# Use dictionaries to store related values of which you wish to lookup later

person = {"name": "jack", "age": 27, "phone number": "555-1234"}

# You can also format a different way that is easier to understand
person = {
  "name": "jack",
  "age": 27,
  "phone number": "555-1234",
}

print(person['name'])  # result "jack"
print(person['age'])  # result 27

# change a value like this
person['age'] = 28
print(person['age']) # result 28

# Add a key, value like this
person['gender'] = 'male'
print(person)  # result {"name": "jack", "age": 28, "phone number": "555-1234", "gender": "male"}

# *** Iteration ***
for k, v in person.items():  # .items() produces two results, the key and the value. In this example they are stored in "k" and "v"
  print(k, v)  # this places each key and value on a new line