A Complete Guide to Python Dictionaries for Beginners
Tags: beginners, python, tutorial
Published: 2022-02-25 14:43:00

## **Table of Contents**

[Introduction](#introduction)
[Definition](#1)
[Creating Python dictionary](#2)
[Accessing dictionary items](#3)
[Changing and Adding Values](#4)
[Removing Items](#5)
[Looping through a Dictionary](#6)
[Dictionary Methods](#7)
[To Sum It Up](#conclusion)

<hr>

## **Introduction** <a name="introduction"></a>

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!

<hr>

## **Definition** <a name="1"></a>

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.

<hr>

## **Creating Python dictionary** <a name="2"></a>

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:**

```py
# 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:**

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

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

**Example:**

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

**Output:**

```py
{1: 'Ayesha', 2: 'Sahar'}
``` 
<hr>

## **Accessing dictionary items** <a name="3"></a>

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:**

```py
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:**

```py
Ali
8
3
``` 
<hr>

## **Changing and Adding Values** <a name="4"></a>

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:**

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

# Changing Values

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

# Adding values

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

**Output: **

```py
{'Name': 'Zahid', 'Age': 23, 'Occupation': 'Manager'}
{'Name': 'Zahid', 'Age': 23, 'Occupation': 'Manager', 'City': 'London'}
```
<hr>
 
## **Removing Items** <a name="5"></a>

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

### **1. pop()**

This method removes the item with the specified key name.

**Example:**

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

thisdict.pop("Age")
print(thisdict)
``` 
**Output:**

```py
{'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:**

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

thisdict.popitem()
print(thisdict)
``` 

**Output:**

```py
{'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:**

```py
# 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:**

```py
{'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:**

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

**Output:**

```py
{}
``` 
<hr>

## **Looping through a Dictionary** <a name="6"></a>

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:**

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

**Output:**

```py
Name
Age
Occupation
``` 
Here’s how to print all values in the dictionary:

**Example:**

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

**Output:**

```py
Zahid
21
Manager
``` 

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

**Example:**

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

**Output:**

```py
Name Zahid
Age 21
Occupation Manager
``` 
<hr>

## **Dictionary Methods** <a name="7"></a>

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

<hr> 

## **To Sum It Up...........** <a name="conclusion"></a>

• 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.

<hr>

**Let's connect!**

✨ [Twitter](https://twitter.com/IAyeshaSahar)  

✨ [Github](https://github.com/AyeshaSahar)