Open In App

Python – Value length dictionary

Last Updated : 22 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with a Python dictionary, we can have problems in which we need to map the value of the dictionary to its length. This kind of application can come in many domains including web development and day-day programming. Let us discuss certain ways in which this task can be performed. 

Method #1 : Using loop + len() 

This is one of the ways in which this task can be performed. In this, we extract the value of the dictionary and map it with its length computed using len() method. 

Python3




# Python3 code to demonstrate working of
# Value length dictionary
# Using loop + len()
 
# initializing dictionary
test_dict = {1: 'gfg', 2: 'is', 3: 'best'}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Value length dictionary
# Using loop + len()
res = {}
for val in test_dict.values():
    res[val] = len(val)
 
# printing result
print("The value-size mapped dictionary is : " + str(res))


Output : 

The original dictionary is : {1: 'gfg', 2: 'is', 3: 'best'}
The value-size mapped dictionary is : {'is': 2, 'best': 4, 'gfg': 3}

Method #2: Using dictionary comprehension

This task can also be performed using dictionary comprehension. In this, we perform tasks similar to the above method, just in a smaller form. 

Python3




# Python3 code to demonstrate working of
# Value length dictionary
# Using dictionary comprehension
 
# initializing dictionary
test_dict = {1: 'gfg', 2: 'is', 3: 'best'}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Value length dictionary
# Using dictionary comprehension
res = {val: len(val) for val in test_dict.values()}
 
# printing result
print("The value-size mapped dictionary is : " + str(res))


Output : 

The original dictionary is : {1: 'gfg', 2: 'is', 3: 'best'}
The value-size mapped dictionary is : {'is': 2, 'best': 4, 'gfg': 3}

Method #3: Here is another approach using map and len functions:

Python3




# Python3 code to demonstrate working of
# Value length dictionary
# Using map() and len()
       
# initializing dictionary
test_dict = {1 : 'gfg', 2 : 'is', 3 : 'best'}
   
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
   
# Value length dictionary
# Using map() and len()
res = dict(map(lambda x: (x[1], len(x[1])), test_dict.items()))
   
# printing result
print("The value-size mapped dictionary is : " + str(res))


Output

The original dictionary is : {1: 'gfg', 2: 'is', 3: 'best'}
The value-size mapped dictionary is : {'gfg': 3, 'is': 2, 'best': 4}

Time complexity: O(n), where n is the number of items in the dictionary.
Auxiliary Space: O(n), as we create a new dictionary to store the value-length mapping.

Method #7: Using collections.defaultdict() and loop

This approach uses the defaultdict() function from the collections module to create a dictionary with default values of 0. Then, a loop is used to iterate over the values of the original dictionary and update the defaultdict with the length of each value.

Steps:

Import the defaultdict function from the collections module
Define the original dictionary and print it
Create a defaultdict with default values of 0
Iterate over the values of the original dictionary and update the defaultdict with the length of each value
Print the new defaultdict

Python3




from collections import defaultdict
 
# initializing dictionary
test_dict = {1: 'gfg', 2: 'is', 3: 'best'}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Value length dictionary using defaultdict and loop
res = defaultdict(int)
for val in test_dict.values():
    res[val] = len(val)
 
# printing result
print("The value-size mapped dictionary is : " + str(dict(res)))


Output

The original dictionary is : {1: 'gfg', 2: 'is', 3: 'best'}
The value-size mapped dictionary is : {'gfg': 3, 'is': 2, 'best': 4}

Time complexity: O(n), where n is the number of items in the dictionary
Auxiliary space: O(n), where n is the number of items in the dictionary



Previous Article
Next Article

Similar Reads

Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python - Replace dictionary value from other dictionary
Given two dictionaries, update the values from other dictionary if key is present in other dictionary. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}, updict = {"Geeks" : 10, "Best" : 17} Output : {'Gfg': 5, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 10} Explanation : "Geeks" and "Best" values updated to 10 and 17. Inpu
6 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Python | Sort dictionary by value list length
While working with Python, one might come to a problem in which one needs to perform a sort on dictionary list value length. This can be typically in case of scoring or any type of count algorithm. Let's discuss a method by which this task can be performed. Method 1: Using sorted() + join() + lambda The combination of above functions can be used to
4 min read
Python - Extract ith Key's Value of K's Maximum value dictionary
Given Dictionary List, extract i'th keys value depending upon Kth key's maximum value. Input : test_list = [{"Gfg" : 3, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}, {"Gfg" : 9, "is" : 16, "best" : 1}], K = "best", i = "is" Output : 11 Explanation : best is max at 19, its corresponding "is" value is 11. Input : test_list = [{"Gfg" :
9 min read
Python - Replace value by Kth index value in Dictionary List
Given a dictionary list, the task is to write a Python program to replace the value of a particular key with kth index of value if the value of the key is list. Examples: Input : test_list = [{'gfg' : [5, 7, 9, 1], 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3, 'gfg' : [7, 3, 9, 1]}], K = 2, key = "gfg" Output : [{'gfg':
7 min read
Python Program to get value of a dictionary given by index of maximum value of given key
Given a dictionary with value as a list, the task is to write a Python program that can find the maximum of any one key and output a similar index column of other key's values. Approach : Get the maximum of the given key.Get the index of the maximum element found.Check if the index of max is present in the search key, if not, return Result not Poss
8 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
Practice Tags :