Dictionary Methods¶
Date published: 2018-03-26
Category: Python
Subcategory: Beginner Concepts
Tags: dictionaries
Dictionaries have methods that allow for modification of dictionary structures. I'll cover a few important ones in this tutorial.
Access dictionary keys¶
The keys() method outputs a dict_keys object that presents a list of a dictionary's keys.
In [2]:
                    Copied!
                    
                    
                dan = {'name': 'Dan Friedman', 'location': 'San Francisco', 'profession': 'Data Scientist'}
dan = {'name': 'Dan Friedman', 'location': 'San Francisco', 'profession': 'Data Scientist'}
        
        In [6]:
                    Copied!
                    
                    
                dan.keys()
dan.keys()
        
        Out[6]:
dict_keys(['name', 'location', 'profession'])
Access dictionary values¶
The values() method outputs a dict_values object that presents a list of a dictionary's values.
In [7]:
                    Copied!
                    
                    
                dan.values()
dan.values()
        
        Out[7]:
dict_values(['Dan Friedman', 'San Francisco', 'Data Scientist'])
Loop over key-value pairs¶
The items() method outputs a dict_items object that's a sequence of tuples in which each tuple is a key-value pair.
In [8]:
                    Copied!
                    
                    
                dan.items()
dan.items()
        
        Out[8]:
dict_items([('name', 'Dan Friedman'), ('location', 'San Francisco'), ('profession', 'Data Scientist')])
We can iterate over this dict_items object in a for loop.
In [10]:
                    Copied!
                    
                    
                for key, value in dan.items():
    print("A key of {0} corresponds to a value of {1}".format(key, value))
for key, value in dan.items():
    print("A key of {0} corresponds to a value of {1}".format(key, value))
        
        A key of name corresponds to a value of Dan Friedman A key of location corresponds to a value of San Francisco A key of profession corresponds to a value of Data Scientist