DEV Community

loading...

Charming the Python: Dictionaries

Vicki (she/her)
Vicki was once a manager of aircraft maintenance and is now charming Python. She coded #VetsWhoCode bot & Code Questions bot. When Vicki isn't petting her cat, she’s throwing a ball for her dogs.
Updated on ・1 min read

If coding tutorials with math examples are the bane of your existence, keep reading. This series uses relatable examples like dogs and cats.


Dictionaries

Dictionaries are collections on mutable/modifiable key-value pairs

Creating

empty_dictionary = {}
dict = {'key1':'value1', 'key2':'value2'}
Enter fullscreen mode Exit fullscreen mode

In the following example, there are booleans, floats, integers, a dictionary, and a list. This list and the dictionary are referred to as "nested" because they are inside another dictionary.

dogs = {
    'name': 'Cheeto',
    'colors': ['tan', 'black'],
    'age': 4.5,
    'chipped': True,
    'breed': 'chihuahua',
    'weight': 12.8,
    'vaccines_due':{
        'rabies': 2022,
        'dhpp': 2020,
        'kennel_cough': 2020,
    }
    }


print(dogs.get('breed'))
>>> chihuahua
Enter fullscreen mode Exit fullscreen mode

Changing

dogs = {
    'name': 'Cheeto',
    'colors': ['tan', 'black'],
    'chipped': True,
    'breed': 'chihuahua',
    'weight': 12.8,
    'vaccines_due':{
        'rabies': 2022,
    }
    }

dogs['fixed'] = True  # adds a new key-value pair
dogs['colors'].append('light tan')  # adds another value to the given key
dogs['name'] = 'Cheese'  # changes value of the given key

print(dogs)
>>> dogs = {
    'name': 'Cheese',
    'colors': ['tan', 'black', 'light tan'],
    'chipped': True,
    'breed': 'chihuahua',
    'weight': 12.8,
    'vaccines_due':{
        'rabies': 2022,
    }
    'fixed': True
    }
Enter fullscreen mode Exit fullscreen mode

Series based on

Discussion (0)