A Complete Guide to Python Dictionaries for Beginners

A Complete Guide to Python Dictionaries for Beginners

Introduction

Python Dictionary is a composite data type. It is an ordered collection of data values that is used to store them. Each Dictionary consists of key-value pairs that are enclosed in curly braces. The keys are unique for each dictionary. The main operations that can be performed on a Dictionary are storing any value with some corresponding key and extracting the value with help of the key. A Dictionary can also be changed as it is mutable. Moreover, there are a lot of useful built-in methods!

Definition

Python dictionary is a collection of items. Each dictionary consists of a collection of key-value pairs. Every key-value pair maps the key to its associated value allowing the dictionary to retrieve values. The key is separated from its value by a colon (:) while the items are separated by commas. A dictionary is enclosed in curly braces. An empty dictionary can be written with two curly braces, like this: {}.

In Python 3.6 and earlier versions, dictionaries were unordered but have been modified to maintain insertion order with the release of Python 3.7 making them an ordered collection of data values.

Creating Python dictionary

Creating a dictionary is no rocket science. It is as simple as placing items inside curly braces {} that are separated by commas. As discussed above, an item has a key and a corresponding value that is expressed as a pair like this: (key: value). The values can be of any data type and can also repeat but the keys must be unique and of immutable type e.g. string, number, or tuple with immutable elements.

Example:

# An empty dictionary
my_dict = {}
print(my_dict)

# A dictionary that has integer keys
my_dict = {1: 'apple', 2: 'mango'}
print(my_dict)

# A dictionary with mixed type keys
my_dict = {'name': 'Ayesha', 1: [5, 10, 13]}
print(my_dict)

Output:

{}
{1: 'apple', 2: 'mango'}
{'name': 'Ayesha', 1: [5, 10, 13]}

A Dictionary can also be created by using the built-in function dict().

Example:

# Creating a Dictionary with dict() method
Dict = dict({1: 'Ayesha', 2: 'Sahar'})
print(Dict)

Output:

{1: 'Ayesha', 2: 'Sahar'}

Accessing dictionary items

In order to access dictionary elements, you can use square brackets along with the key to obtain its value. Another method called get() also helps in accessing any element from a dictionary.

Example:

dict = {'Name': 'Ali', 'Age': 8, 'Grade': '3'}

# Acessing items using []
print(dict['Name'])
print(dict['Age'])

# Acessing items using .get()
print(dict.get('Grade'))

Output:

Ali
8
3

Changing and Adding Values

Python Dictionaries are mutable (changeable). New items can be added or the value of existing items can be easily changed using an assignment operator. If the specified key is present in the dictionary, then the existing value gets updated. If not, a new (key: value) pair is added to the dictionary.

Example:

thisdict =    {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
}

# Changing Values

thisdict["Age"] = 23
print(thisdict)

# Adding values

thisdict['City'] = 'London'
print(thisdict)

Output:

{'Name': 'Zahid', 'Age': 23, 'Occupation': 'Manager'}
{'Name': 'Zahid', 'Age': 23, 'Occupation': 'Manager', 'City': 'London'}

Removing Items

Several methods can be used to remove items from a dictionary.

1. pop()

This method removes the item with the specified key name.

Example:

thisdict =    {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
}

thisdict.pop("Age")
print(thisdict)

Output:

{'Name': 'Zahid', 'Occupation': 'Manager'}

2. popitem()

This method removes the last inserted item (in Python versions 3.6 and below, a random item was removed instead).

Example:

thisdict =    {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
}

thisdict.popitem()
print(thisdict)

Output:

{'Name': 'Zahid', 'Age': 21}

3. del

This keyword removes the item with the specified key name or it can even completely delete a dictionary.

Example:

# Deleting a specified item
thisdict =    {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
}
del thisdict["Age"]
print(thisdict)

# Deleting the whole dictionary 
del thisdict
print(thisdict)

Output:

{'Name': 'Zahid', 'Occupation': 'Manager'} 

#Here we get an error because the dictionary no longer exists!
Traceback (most recent call last):
  File "c:\Users\Dell\Desktop\Dictionary_demo.py", line 11, in <module>
    print(thisdict)
NameError: name 'thisdict' is not defined

4. clear()

This method empties the dictionary.

Example:

thisdict =    {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
}
thisdict.clear()
print(thisdict)

Output:

{}

Looping through a Dictionary

We can loop through a dictionary using for loop. After looping, keys of a dictionary are returned. But through other methods, we can return the values too! Here is an example of printing all keys of a dictionary:

Example:

thisdict =    {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
} 
for x in thisdict:
  print(x)

Output:

Name
Age
Occupation

Here’s how to print all values in the dictionary:

Example:

thisdict =    {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
} 
for x in thisdict:
  print(thisdict[x])

Output:

Zahid
21
Manager

By using the items() method, we can loop through both keys and values. Cool, right?

Example:

thisdict =    {
  "Name": "Zahid",
   "Age": 21,
  "Occupation": "Manager"
} 
for x, y in thisdict.items():
  print(x, y)

Output:

Name Zahid
Age 21
Occupation Manager

Dictionary Methods

Here’s a list of some useful dictionary methods:

1. all()

Returns True if all keys are True or if the dictionary is empty

2. any()

Returns True if any key is true and returns False if the dictionary is empty.

3. len()

Returns the length of dictionary (number of dictionary items).

4. update()

Updates the dictionary with the specified key-value pairs.

5. sorted()

Returns a new but sorted list of all keys in a dictionary.

6. copy()

Returns an exact copy of a dictionary.

7. type()

Returns the data type of the passed variable

To Sum It Up...........

• Python Dictionary is a mutable, ordered collection of data values present in the form of key-value pairs.

• Dictionary items can be accessed through square brackets or by using the get() method.

• Values can be added in a Dictionary by using the assignment operator.

• Items can be removed by using pop(), popitem(), del and clear() methods.

• You can loop through the Dictionary to print either the keys or the values, or you can also print both by using the items() method.

Let's connect!

Twitter

Github