Slice a Dictionary in Python

Vaibhav Vaibhav Jan 30, 2023 Dec 10, 2021
  1. Slice a Dictionary in Python Using Dictionary Comprehension
  2. Slice a Dictionary in Python Using List Comprehension
Slice a Dictionary in Python

Slicing refers to getting a part of the whole. In all programming languages such as Python, C, C++, Java, JavaScript, etc., slicing refers to obtaining a part of a string or a list. A contiguous part of a string and a list is known as substring and subarray. A subsequence is a non-contiguous part of a string or a list.

Dictionary is a data structure that contains key-value pairs. In a dictionary, a hashable unique key points to a value. The value can be anything; an integer, a floating number, a list, a tuple, a set, a dictionary, etc. Dictionaries are generally regarded as maps in other programming langauges, but they perform the same task.

Slicing a dictionary refers to obtaining a subset of key-value pairs present inside the dictionary. Generally, one would filter out values from a dictionary using a list of required keys. In this article, we will learn how to slice a dictionary using Python with the help of some relevant examples.

Slice a Dictionary in Python Using Dictionary Comprehension

Given a non-empty dictionary with key-value pairs and a list of required keys, we can filter out the required key-value pairs by iterating over the dictionary and creating a new dictionary. While iterating over, we have to make sure that the keys inside the list are valid and can be found inside the dictionary. Otherwise, the program will throw annoying exceptions. Refer to the following Python code for the discussed approach.

import json

a = {
    "C": 1.1,
    "O": True,
    "M": "HelloWorld",
    "P": {
        "X": 1,
        "Y": 2,
        "Z": 3
    },
    "U": 25,
    "T": None,
    "E": ["Python", "Is", "Beautiful"],
    "R": [1, 2, 100, 200]
}
targets = ["C", "P", "U"]
result = {key: a[key] for key in a.keys() if key in targets}
print(json.dumps(result, indent = 4))

Output:

{
    "C": 1.1,
    "P": {
        "X": 1,
        "Y": 2,
        "Z": 3
    },
    "U": 25
}

The a variable holds the dictionary, and the targets variable is a list of all the required keys. To create a new dictionary, we are iterating over all the dictionary’s keys and checking if it exists inside the targets. If it does, we add it to our new dictionary. Otherwise, we skip it. This single line of code performs all this creation, filtering, and checking.

result = {key: a[key] for key in a.keys() if key in targets}

This is an inline syntax or dictionary comprehension for iterating over an iterable object and clubbing if and else statements to add more logic and create a new object. This statement may seem a bit complex, but on the contrary, it is really easy and showcases the beauty and power of the Python programming language.

A more straightforward and more basic equivalent Python code of the above Python code is as follows.

import json

a = {
    "C": 1.1,
    "O": True,
    "M": "HelloWorld",
    "P": {
        "X": 1,
        "Y": 2,
        "Z": 3
    },
    "U": 25,
    "T": None,
    "E": ["Python", "Is", "Beautiful"],
    "R": [1, 2, 100, 200]
}
targets = ["C", "P", "U"]
result = {}

for key in a.keys():
    if key in targets:
        result[key] = a[key]
        
print(json.dumps(result, indent = 4))

Output:

{
    "C": 1.1,
    "P": {
        "X": 1,
        "Y": 2,
        "Z": 3
    },
    "U": 25
}

Slice a Dictionary in Python Using List Comprehension

The key-value pairs stored inside a dictionary can be obtained in the form of a list of lists. Given a list of targets, we can iterate over this list of lists and filter out the key that does not exist inside the targets list. Furthermore, we can create a new dictionary using the filtered list of lists. Refer to the following Python code for the above approach.

import json

a = {
    "C": 1.1,
    "O": True,
    "M": "HelloWorld",
    "P": {
        "X": 1,
        "Y": 2,
        "Z": 3
    },
    "U": 25,
    "T": None,
    "E": ["Python", "Is", "Beautiful"],
    "R": [1, 2, 100, 200]
}
targets = ["C", "P", "U"]
result = {}
pairs = a.items()

for (key, value) in pairs:
    if key in targets:
        result[key] = value
        
print(json.dumps(result, indent = 4))

Output:

{
    "C": 1.1,
    "P": {
        "X": 1,
        "Y": 2,
        "Z": 3
    },
    "U": 25
}

The items() method returns an iterable object that contains key-value pairs inside a list. For the above dictionary, the pairs variable looks as follows.

dict_items([('C', 1.1), ('O', True), ('M', 'HelloWorld'), ('P', {'X': 1, 'Y': 2, 'Z': 3}), ('U', 25), ('T', None), ('E', ['Python', 'Is', 'Beautiful']), ('R', [1, 2, 100, 200])])

With a for loop, the values inside the pairs variable are unpacked and filtered with the help of an if statement. The filtered values are then added to the new result dictionary.

All the examples discussed above use the json module to print the dictionary’s output beautifully. Note that the json module has nothing to do with the actual logic for slicing a dictionary, and it is entirely optional to use this module.

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

LinkedIn GitHub

Related Article - Python Dictionary