DEV Community

Cover image for A Complete Guide to Python Dictionaries for Beginners
Ayesha Sahar
Ayesha Sahar

Posted on • Edited on • Originally published at ayeshasahar.hashnode.dev

A Complete Guide to Python Dictionaries for Beginners

Table of Contents

Introduction
Definition
Creating Python dictionary
Accessing dictionary items
Changing and Adding Values
Removing Items
Looping through a Dictionary
Dictionary Methods
To Sum It Up


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)
Enter fullscreen mode Exit fullscreen mode

Output:

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

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{1: 'Ayesha', 2: 'Sahar'}
Enter fullscreen mode Exit fullscreen mode

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'))
Enter fullscreen mode Exit fullscreen mode

Output:

Ali
8
3
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

*Output: *

{'Name': 'Zahid', 'Age': 23, 'Occupation': 'Manager'}
{'Name': 'Zahid', 'Age': 23, 'Occupation': 'Manager', 'City': 'London'}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{'Name': 'Zahid', 'Occupation': 'Manager'}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{'Name': 'Zahid', 'Age': 21}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

4. clear()

This method empties the dictionary.

Example:

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

Output:

{}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

Name
Age
Occupation
Enter fullscreen mode Exit fullscreen mode

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])
Enter fullscreen mode Exit fullscreen mode

Output:

Zahid
21
Manager
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

Name Zahid
Age 21
Occupation Manager
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)