The Wayback Machine - https://web.archive.org/web/20240828111112/https://www.geeksforgeeks.org/python-get-particular-nested-level-items-from-dictionary/
Open In App

Python – Get particular Nested level Items from Dictionary

Last Updated : 14 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a dictionary, extract items from a particular level.

Examples:

Input : {“Gfg” : {  “n1”: 3, “nd2”: { “n2” : 6 }}, “is” : { “ne1”: 5, “ndi2”: { “ne2” : 8, “ne22” : 10 } }}, K = 2 
Output : {‘n2’: 6, ‘ne2’: 8, ‘ne22’: 10} 
Explanation : 2nd nesting items are extracted.

Input : {“Gfg” : { “n1”: 3, “nd2”: { “n2” : 6 }}, “is” : { “ne1”: 5, “ndi2”: { “ne2” : 8, “ne22” : 10 } }}, K = 1 
Output : {“n1”: 3, “ne1”: 5} 
Explanation : Elements of 1st nesting extracted. 

Method #1 : Using isinstance() + recursion

This is one of the ways in which this task can be performed. In this, we perform required recursion for inner nestings, and isinstance is used to differentiate between dict instance and other data types to test for nesting.

Python3




# Python3 code to demonstrate working of
# Get particular Nested level Items from Dictionary
# Using isinstance() + recursion
 
# helper function
 
 
def get_items(test_dict, lvl):
 
    # querying for lowest level
    if lvl == 0:
        yield from ((key, val) for key, val in test_dict.items()
                    if not isinstance(val, dict))
    else:
 
        # recur for inner dictionaries
        yield from ((key1, val1) for val in test_dict.values()
                    if isinstance(val, dict) for key1, val1 in get_items(val, lvl - 1))
 
 
# initializing dictionary
test_dict = {"Gfg": { "n1": 3, "nd2": { "n2": 6 }},
             "is": { "ne1": 5, "ndi2": { "ne2": 8, "ne22": 10 } }}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
K = 2
 
# calling function
res = get_items(test_dict, K)
 
# printing result
print("Required items : " + str(dict(res)))


Output

The original dictionary is : {‘Gfg’: {‘n1’: 3, ‘nd2’: {‘n2’: 6}}, ‘is’: {‘ne1’: 5, ‘ndi2’: {‘ne2’: 8, ‘ne22’: 10}}} Required items : {‘n2’: 6, ‘ne2’: 8, ‘ne22’: 10}

Method #2: Using Stack :

Step by step Algorithm :

  1. Define a function  ‘get_items’ that takes two inputs test_dict and lvl and creates a list named ‘stack’ and appends a tuple of test_dict and lvl.
  2. Create an empty list named ‘items’.
  3. Start a while loop until stack is not empty and inside the loop, pop the last element from the stack and store it in current_dict and current_lvl variables.
  4. Start a for loop for items of the current_dict.
  5. Check if the value of the item is a dictionary or not.
    a) If it is not a dictionary, then check if the current_lvl is 0.
    b) If current_lvl is 0, then append the tuple of key and value in the items list.
    c) If it is a dictionary, then check if the current_lvl is greater than 0.
    d) If it is greater than 0, then append the tuple of the value and current_lvl-1 in the stack list.
  6. Return the items list.
  7. Print the original dictionary and K.
  8. Call the ‘get_items’ function with test_dict and K as input and store the result in res.
  9. Print the required items.

Python3




def get_items(test_dict, lvl):
    stack = [(test_dict, lvl)]
    items = []
    while stack:
        current_dict, current_lvl = stack.pop()
        for key, val in current_dict.items():
            if type(val) != dict:
                if current_lvl == 0:
                    items.append((key, val))
            else:
                if current_lvl > 0:
                    stack.append((val, current_lvl - 1))
    return items
 
test_dict = {"Gfg": { "n1": 3, "nd2": { "n2": 6 }},
             "is": { "ne1": 5, "ndi2": { "ne2": 8, "ne22": 10 } }}
 
print("The original dictionary is : " + str(test_dict))
 
K = 2
 
res = get_items(test_dict, K)
 
print("Required items : " + str(dict(res)))


Output

The original dictionary is : {'Gfg': {'n1': 3, 'nd2': {'n2': 6}}, 'is': {'ne1': 5, 'ndi2': {'ne2': 8, 'ne22': 10}}}
Required items : {'ne2': 8, 'ne22': 10, 'n2': 6}

Complexity Analysis : 

Time complexity: O(n)

The time complexity of this code is O(n), where n is the total number of items in the dictionary. This is because It visits each item only once.

Space complexity: O(m)

The space complexity of this algorithm is O(m), where m is the maximum depth of the nested dictionary. This is because it uses a stack to store the nested dictionaries.



Similar Reads

Three Level Nested Dictionary Python
In Python, a dictionary is a built-in data type used to store data in key-value pairs. Defined with curly braces `{}`, each pair is separated by a colon `:`. This allows for efficient representation and easy access to data, making it a versatile tool for organizing information. What is 3 Level Nested Dictionary?A 3-level nested dictionary refers to
4 min read
Define a 3 Level Nested Dictionary in Python
In Python, dictionaries provide a versatile way to store and organize data. Nested dictionaries, in particular, allow for the creation of multi-level structures. In this article, we'll explore the process of defining a 3-level nested dictionary and demonstrate various methods to achieve this. Define a 3-Level Nested Dictionary in PythonBelow are so
3 min read
How to Loop Three Level Nested Python Dictionary
We are given a three level nested Python Dictionary and our task is to loop through that three level nested Python dictionary. In this article, we will explore two different approaches Nested for loops and Recursion to Loop 3 Level Nested Dictionary Python. Loop Three Level Nested Dictionary PythonBelow are the possible approaches to Loop 3 Level N
3 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
3 Level Nested Dictionary To Multiindex Pandas Dataframe
Pandas is a powerful data manipulation and analysis library for Python. One of its key features is the ability to handle hierarchical indexing, also known as MultiIndexing. This allows you to work with more complex, multi-dimensional data in a structured way. In this article, we will explore how to convert a nested dictionary into a Pandas DataFram
3 min read
Python - Extract values of Particular Key in Nested Values
Given a dictionary with nested dictionaries as values, extract all the values with of particular key. Input : test_dict = {'Gfg' : {"a" : 7, "b" : 9, "c" : 12}, 'is' : {"a" : 15, "b" : 19, "c" : 20}, 'best' :{"a" : 5, "b" : 10, "c" : 2}}, temp = "b" Output : [9, 10, 19] Explanation : All values of "b" key are extracted. Input : test_dict = {'Gfg' :
4 min read
Python | Get items in sorted order from given dictionary
Given a dictionary, the task is to get all items from the dictionary in sorted order. Let's discuss different ways we can do this task. Method #1: Using sorted() C/C++ Code # Python code to demonstrate # to get sorted items from dictionary # initialising _dictionary ini_dict = {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} # printing iniial_diction
3 min read
Python | Get first K items in dictionary
While working with dictionaries, we can come across a problem in which we might have to get just some of the initial keys in dictionary. This problem can typically occur in cases of the web development domain. Let's discuss certain ways in which this problem can be solved. Method #1 : Using items() + list slicing To solve this problem, a combinatio
6 min read
Python Get All Values from Nested Dictionary
In this article, we will learn how we can Get all Values from Nested Dictionary in Python Programming. A nested Dictionary in Python is a dictionary that contains another dictionary as its values. Using this, we can create a nested structure where each of the key-value pairs is in the outer dictionary that points to another dictionary. We will see
5 min read
Python | Count keys with particular value in dictionary
Sometimes, while working with Python dictionaries, we can come across a problem in which we have a particular value, and we need to find frequency if it's occurrence. Let's discuss certain ways in which this problem can be solved. Method #1: Using loop This problem can be solved using naive method of loop. In this we just iterate through each key i
5 min read
Group List of Dictionary Data by Particular Key in Python
Group List of Dictionary Data by Particular Key in Python can be done using itertools.groupby() method. Itertools.groupby() This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items. Syntax: itertools.groupby(iterable, key_func) Parameters: iterable: Iterable can be of any kind (list, tuple,
3 min read
Python - Remove dictionary from a list of dictionaries if a particular value is not present
Given a list of dictionaries, remove all dictionaries which don't have K as a value. Examples: Input : test_list = [{"Gfg" : 4, "is" : 8, "best" : 9}, {"Gfg" : 3, "is": 7, "best" : 5}], K = 7 Output : [{'Gfg': 4, 'is': 8, 'best': 9}] Explanation : Resultant dictionary doesn't contain 7 as any element.Input : test_list = [{"Gfg" : 4, "is" : 7, "best
5 min read
Python Program to find the profit or loss when CP of N items is equal to SP of M items
Given [Tex]N   [/Tex]and [Tex]M   [/Tex]denoting that the Cost Price of N articles is equal to the Selling Price of M articles. The task is to determine the profit or Loss percentage. Examples:  Input: N = 8, M = 9 Output: Loss = -11.11% Input: N = 8, M = 5 Output: Profit = 60% Formula:-  Below is the implementation of the above approach: C/C++ Cod
1 min read
Python - Create nested list containing values as the count of list items
Given a list, the task is to write a Python program to create a nested list where the values are the count of list items. Examples: Input: [1, 2, 3] Output: [[1], [2, 2], [3, 3, 3]] Input: [4, 5] Output: [[1, 1, 1, 1], [2, 2, 2, 2, 2]] Method 1: Using nested list comprehension The list will contain the count of the list items for each element e in
2 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python | Get values of particular key in list of dictionaries
Sometimes, we may require a way in which we have to get all the values of the specific key from a list of dictionaries. This kind of problem has a lot of applications in the web development domain in which we sometimes have a JSON and require just to get a single column from records. Let's discuss certain ways in which this problem can be solved. M
10 min read
Python | Get elements till particular element in list
Sometimes, while working with Python list, we can have a requirement in which we need to remove all the elements after a particular element, or, get all elements before a particular element. These both are similar problems and having a solution to it is always helpful. Let's discuss certain ways in which this task can be performed. Method #1 : Usin
7 min read
Get values of all rows in a particular column in openpyxl - Python
In this article, we will explore how to get the values of all rows in a particular column in a spreadsheet using openpyxl in Python. We will start by discussing the basics of openpyxl and how to install and import it. Then, we will walk through for example, how to extract the values of a particular column from a spreadsheet and store them in a list
4 min read
Get n-smallest values from a particular column in Pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we can get n-smallest values from a particular column in Pandas DataFrame. Observe this dataset first. We'll use 'Age', 'Weight' and 'Salary' columns of this data in order to get n-smallest value
1 min read
Get n-largest values from a particular column in Pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we can get n-largest values from a particular column in Pandas DataFrame. Observe this dataset first. We’ll use ‘Age’, ‘Weight’ and ‘Salary’ columns of this data in order to get n-largest values
1 min read
Get value of a particular cell in PySpark Dataframe
In this article, we are going to get the value of a particular cell in the pyspark dataframe. For this, we will use the collect() function to get the all rows in the dataframe. We can specify the index (cell positions) to the collect function Creating dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession
2 min read
Get a list of a particular column values of a Pandas DataFrame
In this article, we'll see how to get all values of a column in a pandas dataframe in the form of a list. This can be very useful in many situations, suppose we have to get the marks of all the students in a particular subject, get the phone numbers of all the employees, etc. Let's see how we can achieve this with the help of some examples. Pandas
3 min read
Python program to find the sum of all items in a dictionary
Given a dictionary in Python, write a Python program to find the sum of all items in the dictionary. Examples: Input : {'a': 100, 'b':200, 'c':300}Output : 600 Input : {'x': 25, 'y':18, 'z':45}Output : 88 Method #1: Using Inbuilt sum() Function Use the sum function to find the sum of dictionary values. C/C++ Code # Python3 Program to find sum of #
6 min read
Python | Delete items from dictionary while iterating
A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple. Note: In Python 2 dictionary keys were unordered. As of Python 3, they
3 min read
Python | Count number of items in a dictionary value that is a list
In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a key is a list. To check that the value is a list or
5 min read
Python | Type conversion of dictionary items
The interconversion of data types is quite common, and we may have this problem while working with dictionaries as well. We might have a key and corresponding list with numeric alphabets, and we with to transform the whole dictionary to integers rather than string numerics. Let's discuss certain ways in which this task can be performed. Method #1 :
6 min read
Python | Sort the items alphabetically from given dictionary
Given a dictionary, write a Python program to get the alphabetically sorted items from given dictionary and print it. Let’s see some ways we can do this task. Code #1: Using dict.items() C/C++ Code # Python program to sort the items alphabetically from given dictionary # initialising _dictionary dict = {'key2' : 'For', 'key3': 'IsGeeks', 'key1' : '
1 min read
Python - Frequency of unequal items in Dictionary
Sometimes, while working with Python, we can come across a problem in which we need to check for the unequal items count among two dictionaries. This has an application in cases of web development and other domains as well. Let’s discuss certain ways in which this task can be performed. Method #1: Using dictionary comprehension This particular task
5 min read
Python - Common items Dictionary Value List
The functionality of union has been discussed many times. But sometimes, we can have a more complex container, in which we need to check for the intersection of lists which are in form of keys of dictionary. Let’s discuss certain ways to solve this type of problem. Method #1: Using Loops Using loops is a naive brute force approach to perform this p
10 min read
Practice Tags :