Python Beginner Concepts Tutorial
Dictionary Methods
- March 26, 2018
- Key Terms: 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]:
dan = {'name': 'Dan Friedman', 'location': 'San Francisco', 'profession': 'Data Scientist'}
In [6]:
dan.keys()
Out[6]:
Access dictionary values¶
The values()
method outputs a dict_values
object that presents a list of a dictionary's values.
In [7]:
dan.values()
Out[7]:
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]:
dan.items()
Out[8]:
We can iterate over this dict_items
object in a for
loop.
In [10]:
for key, value in dan.items():
print("A key of {0} corresponds to a value of {1}".format(key, value))