Python 3 Dictionary Starter Tutorial

What Is Dictionary In Python?

In the previous chapters, we introduced the two compound types, lists and tuples in Python. In this chapter of our python 3 tutorial, we will present the dictionary type, which is an unordered collection of items in Python. Like lists, dictionary is also mutable and changeable.

Dictionaries and lists have the following same characteristics:

  • Both are mutable and changeable.
  • Both are dynamic. They can grow and shrink as needed.
  • Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.

Dictionaries and lists have the following different characteristics:

  • List elements are accessed by their position in the list, via indexing.
  • Dictionary elements are accessed via keys.

How To Define And Create a Dictionary

The items of dictionary, which are key/value pairs, are separated by commas and enclosed in curly braces. And each key is separated from its value by a colon. The syntax is as follows:

d = {
    <key>: <value>,
    <key>: <value>,
    <key>: <value>

While values can be of any data type and can repeat, keys must be of immutable type (stringnumber or tuple with immutable elements) and must be unique. Here are some classic examples:

# empty dictionary
empty_dict = {}

# dictionary with integer keys
string_dict = {'color': 'red', 'size': '13px', 'name': 'banner'}

# dictionary with mixed keys
mix_dict = {'site': '', 1: [2, 4, 3]}

We can also use the Python built-in function dict() to create a dictionary. So the string_dict dictionary can also be defined like this:

string_dict = dict([('color', 'red'), ('size', '13px'), ('name', 'banner')])

Because the key values of string_dict dictionary are simple strings, here is another way to define string_dict.

string_dict = dict(color = 'red', size = '13px', name = 'banner')

If we know what items should be in the dictionary in advance, then the above ways for creating a dictionary are fine. But what if you want to build a dictionary incrementally and dynamically?

We can create an empty dictionary first, and then add new key-value pairs to the dictionary. For example:

# empty dictionary
string_dict = {}

string_dict['color'] = 'red'
string_dict['size'] = '13px'
string_dict['name'] = 'banner'

#Output: {'color': 'red', 'size': '13px', 'name': 'banner'}

How To Access Values From a Dictionary

As we know, lists and tuples use numeric indexes to access values, while dictionary uses keys. Like lists and tuples, we also use square brackets to access dictionary elements.

string_dict = {'color': 'red', 'size': '13px', 'name': 'banner'}

# Output: red

If the key is not in the specified dictionary, the python program will throw a KeyError exception.

>>> string_dict['user']
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
KeyError: 'user'

We can also get the item through the dictionary’s built-in function get():

string_dict = {'color': 'red', 'size': '13px', 'name': 'banner'}

# Output: 13px

The difference while using get() is that it returns None instead of KeyError, if the key is not found.

How To Change Items From a Dictionary

As mentioned at the beginning of the chapter, dictionary is mutable and changeable. That is, we can add new items or change the value of existing items using assignment operator.

string_dict = {'color': 'red', 'size': '13px', 'name': 'banner'}

# update value
string_dict['age'] = 'green'

#Output: {'color': 'green', 'size': '13px', 'name': 'banner'}

# add item
string_dict['id'] = 'banner_id'  

# Output: {'id': 'banner_id', 'color': 'red', 'size': '13px', 'name': 'banner'}

At the same time, we can also remove items that are no longer needed using the following 4 ways.

del: It can remove individual items or delete the entire dictionary. For example:

string_dict = {'color': 'red', 'size': '13px', 'name': 'banner'}

# delete a particular item
del string_dict['color']
#Output: {'size': '13px', 'name': 'banner'}
print (string_dict)

# delete the dictionary itself
del string_dict
# Throws Error
# print(string_dict)

pop() method: Delete the value corresponding to the given key of the dictionary, and return the deleted value. For example:

string_dict = {'color': 'red', 'size': '13px', 'name': 'banner'}

# remove a particular item
pop_color = string_dict.pop('color')
#Output: red

popitem() method: Delete the random item in the dictionary and return the key-value pair which is removed. For example:

string_dict = {'color': 'red', 'size': '13px', 'name': 'banner'}

# remove an arbitrary item
pop_obj = string_dict.popitem()
#The output may be: {'color': 'red'}

clear() method: Empty all items in the dictionary. For example:

string_dict = {'color': 'red', 'size': '13px', 'name': 'banner'}

# remove all items
#Output: {}

Built-in Functions

The Python dictionary contains the following built-in functions:

len(dict)Get the number of items in a dictionary, which is the total number of keys.string_dict = {'color': 'red', 'size': '13px', 'name': 'banner'} len(string_dict) 3
str(dict)Output the dictionary as a string.string_dict = {'color': 'red', 'size': '13px', 'name': 'banner'} str(string_dict) "{'color': 'red', 'size': '13px', 'name': 'banner'}"
type(variable)Returns the variable type.string_dict = {'color': 'red', 'size': '13px', 'name': 'banner'} type(string_dict) <class 'dict'>

Built-in Methods

The Python dictionary contains the following built-in methods:

d.clear()Clears a dictionary.
d.get(<key>[, <default>])Returns the value for a key if it exists in the dictionary.
d.items()Returns a list of key-value pairs in a dictionary.
d.keys()Returns a list of keys in a dictionary.
d.values()Returns a list of values in a dictionary.
d.pop(<key>[, <default>])Removes a key from a dictionary, if it is present, and returns its value.
d.popitem()Removes a key-value pair from a dictionary.
d.update(<obj>)Merges a dictionary with another dictionary or with an iterable of key-value pairs.

Next you will learn about Python sets. The set is another composite data type, but it is quite different from either a list or dictionary.

Leave a Comment

Your email address will not be published.