Python

Python Dictionaries

A dictionary in Python is a collection of key-value pairs. The dictionary is surrounded by curly braces. Each pair is separated by a comma and the key and value are separated by a colon. Here is an example:


state_capitals = {
    'Arkansas': 'Little Rock',
    'Colorado': 'Denver',
    'California': 'Sacramento',
    'Georgia': 'Atlanta'

 

To get a value, refer to it by its key:


ca_capital = state_capitals['California']

 

You can also get all of the keys in a dictionary and then iterate over them: 


for k in state_capitals.keys():

       print('{} is the capital of {}'.format(state_capitals[k], k))


Dictionaries strongly resemble JSON syntax. The native json module in the Python standard library can be used to convert between JSON and dictionaries.