Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - Dictionary

Python

python logo

In this tutorial we will learn about dictionary in Python.

We briefly talked about dictionary in the Python - Data Type tutorial.

What is a dictionary?

A dictionary is an unordered collection of key-value pairs.

We use curly { } brackets to create dictionary and separate key from value using : colon. Each pair of the dictionary is separated by , comma.

In the following example we are creating a dictionary of user data.

# dictionary
user = {
  "username": "yusufshakeel",
  "isOnline": False,
  "score": 9.1
}

# output
print("type:", type(user))
print(user)

We will get the following output.

type: <class 'dict'>
{'username': 'yusufshakeel', 'isOnline': False, 'score': 9.1}

The dict() constructor

We use the dict() constructor to create a dictionary in Python.

# dictionary
user = dict(username = "yusufshakeel", isOnline = False, score = 9.1)

#output
print(user)

Output

{'username': 'yusufshakeel', 'isOnline': False, 'score': 9.1}

Accessing dictionary items

A dictionary item is a key-value pair so, to get the value we use the key.

Following is the syntax to get the value of a given key of a dictionary.

dictionary[key]

Where, dictionary represents a dictionary variable and key is some key whose value we are trying to access.

In the following Python program we are printing the value saved in a "username" key of a "user" dictionary.

# dictionary
user = {
  "username": "yusufshakeel",
  "isOnline": False,
  "score": 9.1
}

# output
print(user['username'])      # yusufshakeel

If the key does not exists in the dictionary then we get an error.

Accessing dictionary items using get method

We can also get the value of a key using the get method.

In the following Python program we are printing the score.

# dictionary
user = {
  "username": "yusufshakeel",
  "isOnline": False,
  "score": 9.1
}

# output
print(user.get('score'))     # 9.1

If the key does not exists then get will return None of NoneType class.

In the following Python program we are trying to get the value of a key that does not exists.

# dictionary
user = {
  "username": "yusufshakeel",
  "isOnline": False,
  "score": 9.1
}

value = user.get('unknown')

# output
print("type:", type(value))
print("value:", value)

We will get the following output.

type: <class 'NoneType'>
value: None

Change value of dictionary item

We use the following syntax to change the value of a dictionary item.

dictionary[key] = value

Where, dictionary represents a dictionary variable, key is some key whose value we want to change and value is the new value that we are assigning to the key.

In the following Python program we are assigning True to isOnline key.

# dictionary
user = {
  "username": "yusufshakeel",
  "isOnline": False,
  "score": 9.1
}

# change
user['isOnline'] = True

# output
print(user)

Output:

{'username': 'yusufshakeel', 'isOnline': True, 'score': 9.1}

Print all the keys of a dictionary

We take help of for loop to print all the keys of a dictionary.

In the following Python program we are printing out all the keys of the user dictionary.

# dictionary
user = {
  "username": "yusufshakeel",
  "isOnline": False,
  "score": 9.1
}

for k in user:
    print(k)

We will get the following output.

username
isOnline
score

Printing key-value pairs of a dictionary

To print the key-value pairs of a dictionary we take help of the for loop.

So, the for loop helps us to get the key of the dictionary. Then using the key we can access the value.

In the following Python program we are printing the key-value pairs.

# dictionary
user = {
  "username": "yusufshakeel",
  "isOnline": False,
  "score": 9.1
}

for k in user:
  print("key:", k, "value:", user[k])

Output:

key: username value: yusufshakeel
key: isOnline value: False
key: score value: 9.1

Check existence of a key

To check if a key exists in a given dictionary we take help of the in - membership operator.

The in operator will return True if the key exists. False otherwise.

In the following example we are checking the existence of some items in a given dictionary.

# dictionary
user = {
  "username": "yusufshakeel",
  "isOnline": False,
  "score": 9.1
}

# output
print("username" in user)   # True
print("score" in user)      # True
print("unknown" in user)    # False

Counting dictionary items

We use the len method to count the total number of items (key-value pairs) present in a given dictionary.

In the following Python program we are printing the total number of items.

# dictionary
user = {
    "username": "yusufshakeel",
    "isOnline": False,
    "score": 9.1
}

# output
print(len(user))     # 3

Adding new item to dictionary

We use the following syntax to add a new item to an existing dictionary.

dictionary[key] = value

Where, dictionary represents a dictionary variable and key is the new item key that we want to add to the dictionary and value is the value of the new item.

In the following Python program we are adding a new item to the user dictionary.

# dictionary
user = {
    "username": "yusufshakeel",
    "isOnline": False,
    "score": 9.1
}

# new item
user["level"] = 1

# output
print(user)

We will get the following output.

{'username': 'yusufshakeel', 'isOnline': False, 'score': 9.1, 'level': 1}

Pop dictionary items

We use the pop method to pop (remove) items from a given dictionary.

In the following example we are popping out "level" item from the user dictionary.

# dictionary
user = {
    "username": "yusufshakeel",
    "isOnline": False,
    "score": 9.1,
    "level": 1
}

# pop
itemValue = user.pop('level')

# output
print(itemValue)  # 1
print(user)       # {'username': 'yusufshakeel', 'isOnline': False, 'score': 9.1}

Note! The pop method will remove the item from the list and will return the value that was removed which we can save in some variable.

Delete dictionary items

We can also use the del keyword to delete items from the dictionary.

In the following Python program we are deleting "level" from the user dictionary using the del keyword.

# dictionary
user = {
    "username": "yusufshakeel",
    "isOnline": False,
    "score": 9.1,
    "level": 1
}

# delete
del user['level']

# output
print(user)    # {'username': 'yusufshakeel', 'isOnline': False, 'score': 9.1}

Delete dictionary

We can also use the del keyword to completely delete the dictionary and all the items.

In the following Python program we are deleting the user dictionary.

# dictionary
user = {
    "username": "yusufshakeel",
    "isOnline": False,
    "score": 9.1,
    "level": 1
}

# delete
del user