Dictionaries: Constructing A Dictionary
Dictionaries: Constructing A Dictionary
Dictionaries
We've been learning about sequences in Python but now we're going to switch gears and learn about
mappings in Python. If you're familiar with other languages you can think of these Dictionaries as hash
tables.
This section will serve as a brief introduction to dictionaries and consist of:
So what are mappings? Mappings are a collection of objects that are stored by a key, unlike a sequence that
stored objects by their relative position. This is an important distinction, since mappings won't retain order
since they have objects defined by a key.
A Python dictionary consists of a key and then an associated value. That value can be almost any Python
object.
Constructing a Dictionary ¶
Let's see how we can construct dictionaries to get a better understanding of how they work!
In [1]:
In [2]:
Out[2]:
'value2'
Its important to note that dictionaries are very flexible in the data types they can hold. For example:
In [3]:
my_dict = {'key1':123,'key2':[12,23,33],'key3':['item0','item1','item2']}
In [4]:
Out[4]:
In [5]:
Out[5]:
'item0'
In [6]:
Out[6]:
'ITEM0'
In [7]:
my_dict['key1']
Out[7]:
123
In [8]:
In [9]:
#Check
my_dict['key1']
Out[9]:
A quick note, Python has a built-in method of doing a self subtraction or addition (or multiplication or division).
We could have also used += or -= for the above statement. For example:
In [10]:
Out[10]:
-123
We can also create keys by assignment. For instance if we started off with an empty dictionary, we could
continually add to it:
In [11]:
In [12]:
In [13]:
In [14]:
#Show
d
Out[14]:
In [15]:
Wow! That's a quite the inception of dictionaries! Let's see how we can grab that value:
In [16]:
Out[16]:
'value'
In [17]:
In [18]:
Out[18]:
In [19]:
Out[19]:
dict_values([1, 2, 3])
In [20]:
# Method to return tuples of all items (we'll learn about tuples soon)
d.items()
Out[20]:
Hopefully you now have a good basic understanding how to construct dictionaries. There's a lot more to go
into here, but we will revisit dictionaries at later time. After this section all you need to know is how to create a
dictionary and how to retrieve values from it.