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 Methods

Python

python logo

In this tutorial we will learn about dictionary methods in Python.

In the previous tutorial Python - Dictionary we learned about dictionary. Feel free to check that out.

Quick recap

  • A dictionary is an unordered collection of key-value pairs.
  • We use curly { } brackets to create dictionary.
  • The key is separated from the value using : colon.
  • Each key-value pair of the dictionary is separated by , comma.

Alright, let's get started with dictionary methods.

clear

We use the clear method to remove all the items from the dictionary.

In the following Python program we are removing all the items from the given dictionary.

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

user.clear()

copy

We use the copy method to make a copy of an existing dictionary.

In the following Python program we are creating a copy of a given dictionary.

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

x = user.copy()

fromkeys

We use the fromkeys method to create a dictionary with given keys and values.

In the following Python program we are creating a dictionary using keys passed to the fromkeys method.

# keys
keys = ("a", "b", "c")

myDict = dict.fromkeys(keys)

print(myDict)

We will get the following output.

{'a': None, 'b': None, 'c': None}

Note! If the value is not passed then None is used as the default value.

In the following Python program we are creating a dictionary using the keys passed to the fromkeys method and we are setting all the keys to 0.

# keys and value
keys = ("a", "b", "c")
value = 0

myDict = dict.fromkeys(keys, value)

print(myDict)     # {'a': 0, 'b': 0, 'c': 0}

get

We use the get method to get value of a specific key of a given dictionary.

In the following Python program we are getting the value of the "score" key.

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

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

Note! If the key does not exists in the given dictionary then we will get None.

items

We use the items method to get a list that consists of tuples made up of key-value pairs of a given dictionary.

In the following Python program we are creating a dictionary list using the items method.

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

items = user.items()

print(items)

We will get the following output.

dict_items([('username', 'yusufshakeel'), ('score', 9.1), ('isOnline', False)])

keys

We use the keys method to get all the keys of a given dictionary.

In the following Python program we are getting the keys.

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

keys = user.keys()

print(keys)

We will get the following output.

dict_keys(['username', 'score', 'isOnline'])

pop

We use the pop method to remove a specific item (key-value pair) from the dictionary using a given key.

In the following Python program we are removing the "isGameOver" item from the dictionary using the pop method.

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

item = user.pop('isGameOver')

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

popitem

We use the popitem to remove the last inserted item from the dictionary.

In the following Python program we are inserting a new item and then popping it.

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

# insert item
user['isGameOver'] = False

print("before:", user)

# pop item
item = user.popitem()

print("popitem:", item)

print("after:", user)

Output

before: {'username': 'yusufshakeel', 'score': 9.1, 'isOnline': False, 'isGameOver': False}
popitem: ('isGameOver', False)
after: {'username': 'yusufshakeel', 'score': 9.1, 'isOnline': False}

setdefault

We use the setdefault method to get the value of a specified key.

If the key does not exists in the dictionary then the key is inserted with the given value passed to the setdefault method.

In the following Python program we will get back the value of "score" key as it exists in the dictionary.

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

item = user.setdefault('score', 9.2)

print(item)
print(user)

Output:

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

In the following Python program the key "isGameOver" is added to the dictionary as it does not exists.

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

item = user.setdefault('isGameOver', False)

print(item)
print(user)

Output

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

update

We use the update method to insert an item in the dictionary.

In the following Python program we are inserting a new item (key-value pair) isGameOver: False in the given dictionary.

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

user.update({'isGameOver': False})

print(user)

Output:

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

values

We use the values method to get all the values of a dictionary.

In the following Python program we are printing all the values of a given dictionary.

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

values = user.values()

print(values)

We will get the following output.

dict_values(['yusufshakeel', 9.1, False])

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT