Python Dictionaries

Python dictionaries are an unordered collection of key-value pairs. Dictionaries are a mappings data type used to store collections of data.

The 4 data types that store collections are: dictionaries, lists, sets and tuples, which we’ll cover in other lessons.

Example Python Dictionary

Python dictionaries are created using curl brackets ({})

Join the Newsletter

    # Example Dictionary
    d = {
            'name': 'JC', 
            'last_name': 'Chouinard'
        }
    d
    

    In the output, we know that the element is a dictionary based on the curly brackets.

    {'name': 'JC', 'last_name': 'Chouinard'}
    

    Dictionaries don’t allow duplicates

    # No duplicates
    {
        'name': 'JC', 
        'name': 'JC'
    }
    

    The output does not show duplicate values.

    {'name': 'JC'}
    

    Dictionaries Have Keys and Values

    ## Key,value pairs
    d = {
        'a':1,
        'b':2,
        'c':3
    }
    
    # Access the value using the key
    d['a']
    
    1
    

    Values Can Have Multiple Data Types

    # Storing data types in dicts
    d = {
        'str':'hello',
        'bool':False,
        'list':[1,2,3],
        'int':10
    }
    print(type(d))
    print(type(d['bool']))
    
    <class 'dict'>
    <class 'bool'>
    

    Creating a Dictionary

    Create an empty dictionary

    # Initialize empty dictionary
    d = dict()
    print(d)
    d = {}
    print(d)
    
    {}
    {}
    

    Create a Dictionary Using a Constructor

    # Constructor
    dict(name='JC',last_name='Chouinard')
    
    {'name': 'JC', 'last_name': 'Chouinard'}
    

    Create a Dictionary From Keys

    # Create dict from keys
    keys = ['a','b','c']
    value = 0
    dict.fromkeys(keys,value)
    
    {'a': 0, 'b': 0, 'c': 0}
    

    Searching a Dictionary

    Let’s talk about how to search through a dictionary.

    Take this dictionary to start with:

    # create dict 
    my_dict = dict(
        name='David',
        last_name='Attenborough',
        birth='1926-05-09',
        occupations=['Broadcaster','naturalist'],
        family={
            'spouse':'Jane Ebsworth Oriel',
            'children':2
            }
        )
    my_dict
    
    {'name': 'David',
     'last_name': 'Attenborough',
     'birth': '1926-05-09',
     'occupations': ['Broadcaster', 'naturalist'],
     'family': {'spouse': 'Jane Ebsworth Oriel', 'children': 2}}
    

    Show Dictionary Keys

    # Keys
    my_dict.keys()
    
    dict_keys(['name', 'last_name', 'birth', 'occupations', 'family'])
    

    Show Dictionary Values

    # Values
    my_dict.values()
    
    dict_values(['David', 'Attenborough', '1926-05-09', ['Broadcaster', 'naturalist'], {'spouse': 'Jane Ebsworth Oriel', 'children': 2}])
    

    Search Dictionary Value using Get

    # Get
    my_dict.get('name')
    
    'David'
    

    Search Dictionary Nested-Value using Get

    # Keys
    my_dict.keys()
    
    dict_keys(['name', 'last_name', 'birth', 'occupations', 'family'])
    
    # Nested Dict
    my_dict['family'].get('spouse')
    
    'Jane Ebsworth Oriel'
    
    # Nested Dict
    my_dict['family']['spouse']
    
    'Jane Ebsworth Oriel'
    

    Modify Values of Python Dictionaries

    Modify a Single Value

    # Modify value
    my_dict['birth'] = '1926-05-08'
    my_dict['birth'] 
    
    '1926-05-08'
    

    Add Items

    # Assign value to key
    my_dict['known_for'] = 'Wildife Documentaries'
    my_dict['known_for']
    
    'Wildife Documentaries'
    

    Perform Multiple Changes at Once

    # Perform multiple changes at once
    my_dict.update({
        'known_for':'Planet Earth',
        'works_for':'BBC'
    })
    
    my_dict
    
    {'name': 'David',
     'last_name': 'Attenborough',
     'birth': '1926-05-08',
     'occupations': ['Broadcaster', 'naturalist'],
     'family': {'spouse': 'Jane Ebsworth Oriel', 'children': 2},
     'known_for': 'Planet Earth',
     'works_for': 'BBC'}
    

    Remove Items from a Dictionary

    Remove Specific Item from a Python Dictionary

    # Remove specific Item
    my_dict.pop('birth')
    my_dict
    
    {'name': 'David',
     'last_name': 'Attenborough',
     'occupations': ['Broadcaster', 'naturalist'],
     'family': {'spouse': 'Jane Ebsworth Oriel', 'children': 2},
     'known_for': 'Planet Earth',
     'works_for': 'BBC'}
    

    Remove Last Item from a Dictionary

    # Remove last item
    my_dict.popitem()
    my_dict
    
    {'name': 'David',
     'last_name': 'Attenborough',
     'occupations': ['Broadcaster', 'naturalist'],
     'family': {'spouse': 'Jane Ebsworth Oriel', 'children': 2},
     'known_for': 'Planet Earth'}
    

    Looping Through a Python Dictionary

    # Create dict
    my_dict = dict(
        name='JC',
        last_name='Chouinard',
        domain='jcchouinard.com',
        twitter='ChouinardJC'
    )
    

    Loop and Print Dictionary Keys

    Two ways to loop through a dictionary and print its keys.

    # Print Keys
    for x in my_dict:
        print(x)
    
    name
    last_name
    domain
    twitter
    
    # Print Keys
    for x in my_dict.keys():
        print(x)
    
    name
    last_name
    domain
    twitter
    

    Loop and Print Dictionary Values

    Two ways to loop through a dictionary and print its values.

    # Print values
    for x in my_dict:
        print(my_dict[x])
    
    JC
    Chouinard
    jcchouinard.com
    ChouinardJC
    
    # print values
    for x in my_dict.values():
        print(x)
    
    JC
    Chouinard
    jcchouinard.com
    ChouinardJC
    

    Loop and Print Dictionary Keys and Values

    Use the items() method on the dictionary to loop through each key, value pair.

    # Print Keys and values
    for x in my_dict.items():
        print(x[0], x[1])
    
    name JC
    last_name Chouinard
    domain jcchouinard.com
    twitter ChouinardJC
    

    Other Python Dictionary Methods

    # Create dict
    my_dict = dict(
        name='JC',
        last_name='Chouinard',
        domain='jcchouinard.com',
        twitter='ChouinardJC'
    )
    

    Add if not Existing: setdefault()

    # Add if not existing
    my_dict.setdefault('employer','Tripadvisor')
    my_dict
    
    {'name': 'JC',
     'last_name': 'Chouinard',
     'domain': 'jcchouinard.com',
     'twitter': 'ChouinardJC',
     'employer': 'Tripadvisor'}
    
    # But don't change if key exist
    my_dict.setdefault('name','Jean-Christophe')
    my_dict
    
    {'name': 'JC',
     'last_name': 'Chouinard',
     'domain': 'jcchouinard.com',
     'twitter': 'ChouinardJC',
     'employer': 'Tripadvisor'}
    

    Clear Dictionary: clear()

    # Empty dict
    my_dict.clear()
    my_dict
    
    {}
    

    Conclusion

    This was a very simple introduction to Python Dictionaries.

    Enjoyed This Post?