Python Dictionaries

Updated: Aug 21, 2020




Python Dictionaries


A dictionary is a collection that is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values.


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.


Dictionaries cannot be sorted.



Constructing a Dictionary


Let's see how we can construct dictionaries to get a better understanding of how they work!


Example:


# Make a dictionary with {} and : to signify a key and a value
my_dict={'key1':'value1','key2':'value2'}


# Call values by their key
print(my_dict['key2'])

Output:

'value2'


It is important to note that dictionaries are very flexible in the data types they can hold. For example



Example:


# Create a dictionary 
my_dict={'key1':123,'key2':[12,23,33],'key3':['item0','item1','item2']}


# Let's call items from the dictionary
print(my_dict['key3'])

Output:

 
 ['item0', 'item1', 'item2']
 


Example:


# Can call an index on that value 
print(my_dict['key3'][0])

Output:

 
 item0
 


Example:


# Can then even call methods on that value 
print(my_dict['key3'][0].upper())

Output:


ITEM0



We can affect the values of a key as well. For instance:


Example:

  
print(my_dict['key1'])
  

Output:


123



Example:


# Subtract 123 from the value 
my_dict['key1'] = my_dict['key1'] - 123


# Check
print(my_dict['key1'])

Output:


0



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.


Example:


# Set the object equal to itself minus 123  
my_dict['key1'] -= 123 
print(my_dict['key1'])

Output:


-123



We can also create keys by assignment. For instance if we started off with an empty dictionary, we could continually add to it:


Example:


# Create a new dictionary
d = {}


# Create a new key through assignment 
d['animal'] = 'Dog'


# Can do this with any object 
d['answer'] = 42


# Show 
print(d)

Output:


{'animal': 'Dog', 'answer': 42}



Nesting with Dictionaries


Hopefully, you're starting to see how powerful Python is with its flexibility of nesting objects and calling methods on them. Let's see a dictionary nested inside a dictionary.


Example:


# Dictionary nested inside a dictionary nested inside a dictionary
d={'key1':{'nestkey':{'subnestkey':'value'}}}

Wow! That's quite the inception of dictionaries! Let's see how we can grab that value.


Example:


# Keep calling the keys 
print(d['key1']['nestkey']['subnestkey'])

Output:


value



A few Dictionary Methods


There are a few methods we can call on a dictionary. Let's get a quick introduction to a few of them.


Example:


# Create a typical dictionary 
d = {'key1':1,'key2':2,'key3':3}


# Method to return a list of all keys 
print(d.keys())

Output:


dict_keys(['key1', 'key2', 'key3'])



Example:


# Method to grab all values 
print(d.values())

Output:


dict_values([1, 2, 3])



Example:


# Method to return tuples of all items  (we'll learn about tuples soon)
print(d.items())

Output:

 
 dict_items([('key1', 1), ('key2', 2), ('key3', 3)])
 


FAQ


Do dictionaries keep an order? How do I print the values of the dictionary in order?

Dictionaries are mappings and do not retain order! If you do want the capabilities of a dictionary but you would like ordering as well, check out the ordereddict object that we are going to discuss in the upcoming articles



Hopefully, you now have a good basic understanding of how to construct dictionaries.




Next is the tuple data type.

Happy learning :-)










39 views0 comments

Recent Posts

See All