Dictionary in Python
is a collection of keys values, used to store data values like a map, which, unlike
other data types which hold only a single value as an element.
Example of Dictionary in Python
Dictionary holds key:value pair. Key-Value is provided in the dictionary to make it more optimized.
Python3
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(Dict)
Output:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Creating a Dictionary
In Python, a dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’. Dictionary holds pairs of values, one being the Key and the other
corresponding pair element being its Key:value. Values in a dictionary can be of any data type and
can be duplicated, whereas keys can’t be repeated and must be immutable.
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be treated
distinctly.
Python3
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Output:
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{'Name': 'Geeks', 1: [1, 2, 3, 4]}
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by
just placing to curly braces{}.
Python3
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}
Complexities for Creating a Dictionary:
Time complexity: O(len(dict))
Space complexity: O(n)
Nested Dictionary
Python3
# Creating a Nested Dictionary
# as shown in the below image
Dict = {1: 'Geeks', 2: 'For',
3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
print(Dict)
Output:
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
Adding elements to a Dictionary
Addition of elements can be done in multiple ways. One value at a time can be added to a Dictionary
by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing value in a
Dictionary can be done by using the built-in update() method. Nested key values can also be added
to an existing Dictionary.
Note- While adding a value, if the key-value already exists, the value gets updated otherwise a new
Key with the value is added to the Dictionary.
Python3
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements one at a time
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested': {'1': 'Life', '2': 'Geeks'}}
print("\nAdding a Nested Key: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5:
{'Nested': {'1': 'Life', '2': 'Geeks'}}}
Complexities for Adding elements in a Dictionary:
Time complexity: O(1)/O(n)
Space complexity: O(1)
Accessing elements of a Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets.
Python3
# Python program to demonstrate
# accessing a element from a Dictionary
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using key
print("Accessing a element using key:")
print(Dict['name'])
# accessing a element using key
print("Accessing a element using key:")
print(Dict[1])
Output:
Accessing a element using key:
For
Accessing a element using key:
Geeks
There is also a method called get() that will also help in accessing the element from a dictionary.This
method accepts key as argument and returns the value.
Complexities for Accessing elements in a Dictionary:
Time complexity: O(1)
Space complexity: O(1)
Python3
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using get()
# method
print("Accessing a element using get:")
print(Dict.get(3))
Output:
Accessing a element using get:
Geeks
Accessing an element of a nested dictionary
In order to access the value of any key in the nested dictionary, use indexing [] syntax.
Python3
# Creating a Dictionary
Dict = {'Dict1': {1: 'Geeks'},
'Dict2': {'Name': 'For'}}
# Accessing element using key
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
Output:
{1: 'Geeks'}
Geeks
For
Deleting Elements using del Keyword
The items of the dictionary can be deleted by using the del keyword as given below.
Python3
# Python program to demonstrate
# Deleting Elements using del Keyword
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print("Dictionary =")
print(Dict)
#Deleting some of the Dictionar data
del(Dict[1])
print("Data after deletion Dictionary=")
print(Dict)
Output
Dictionary ={1: 'Geeks', 'name': 'For', 3: 'Geeks'}
Data after deletion Dictionary={'name': 'For', 3: 'Geeks'}
Dictionary methods
Method Description
dic.clear() Remove all the elements from the dictionary
dict.copy() Returns a copy of the dictionary
dict.get(key, default = “None”) Returns the value of specified key
dict.items() Returns a list containing a tuple for each key value pair
dict.keys() Returns a list containing dictionary’s keys
dict.update(dict2) Updates dictionary with specified key-value pairs
dict.values() Returns a list of all the values of dictionary
pop() Remove the element with specified key
popItem() Removes the last inserted key-value pair
dict.setdefault(key,default= set the key to the default value if the key is not specified in
“None”) the dictionary
dict.has_key(key) returns true if the dictionary contains the specified key.
dict.get(key, default = “None”) used to get the value specified for the passed key.
Python3
# demo for all dictionary methods
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
# copy() method
dict2 = dict1.copy()
print(dict2)
# clear() method
dict1.clear()
print(dict1)
# get() method
print(dict2.get(1))
# items() method
print(dict2.items())
# keys() method
print(dict2.keys())
# pop() method
dict2.pop(4)
print(dict2)
# popitem() method
dict2.popitem()
print(dict2)
# update() method
dict2.update({3: "Scala"})
print(dict2)
# values() method
print(dict2.values())
Output:
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])
Python | Convert flattened dictionary into nested dictionary
garg_ak0109
Read
Discuss
Courses
Practice
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
function iterates over all elements of the input list except the last two elements, and creates nested
dictionaries corresponding to each element in the list.
The insert() function then updates the dictionary (dct) with a key-value pair where the key is the
second last element of the input list, and the value is the last element of the input list.
Define a function named convert_nested that takes a dictionary (dct) as an input. This function first
initializes an empty dictionary named result to store the output nested dictionary.
The function then creates an iterator named lists, which is a list of lists where each list represents a
hierarchical flow of keys and values from the input dictionary. To create this iterator, it splits each
key of the input dictionary by the ‘_’ character and appends the corresponding value to the list.
The convert_nested() function then iterates over each list in the lists iterator and inserts it into the
result dictionary using the insert() function.
Finally, the convert_nested() function returns the resulting nested dictionary result.
Define an initial dictionary named ini_dict containing key-value pairs.
Print the initial dictionary using the print() function.
Create a new list named _split_dict that contains lists representing the hierarchical flow of keys and
values from the initial dictionary by splitting each key of the dictionary by the ‘_’ character and
appending the corresponding value to the list.
Print the final nested dictionary by calling the convert_nested() function on the initial dictionary and
print the resulting nested dictionary using the print() function.
Below is the implementation of the above approach:
Python3
# Python code to demonstrate
# conversion of flattened dictionary
# into nested dictionary
def insert(dct, lst):
for x in lst[:-2]:
dct[x] = dct = dct.get(x, dict())
dct.update({lst[-2]: lst[-1]})
def convert_nested(dct):
# empty dict to store the result
result = dict()
# create an iterator of lists
# representing nested or hierarchical flow
lists = ([*k.split("_"), v] for k, v in dct.items())
# insert each list into the result
for lst in lists:
insert(result, lst)
return result
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
# printing initial dictionary
print ("initial_dictionary", str(ini_dict))
# code to convert ini_dict to nested
# dictionary splitting_dict_keys
_split_dict = [[*a.split('_'), b] for a, b in ini_dict.items()]
# printing final dictionary
print ("final_dictionary", str(convert_nested(ini_dict)))
Output
initial_dictionary {'Geeks_for_for': 1, 'Geeks_for_geeks': 4, 'for_geeks_Geeks': 3, 'geeks_Geeks_for':
7}
final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks':
{'for': 7}}}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using default dict and recursive approach
Python3
# Python code to demonstrate
# conversion of flattened dictionary
# into nested dictionary
# code to convert dict into nested dict
def nest_dict(dict1):
result = {}
for k, v in dict1.items():
# for each key call method split_rec which
# will split keys to form recursively
# nested dictionary
split_rec(k, v, result)
return result
def split_rec(k, v, out):
# splitting keys in dict
# calling_recursively to break items on '_'
k, *rest = k.split('_', 1)
if rest:
split_rec(rest[0], v, out.setdefault(k, {}))
else:
out[k] = v
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
# printing initial dictionary
print ("initial_dictionary", str(ini_dict))
# printing final dictionary
print ("final_dictionary", str(nest_dict(ini_dict)))
Output
initial_dictionary {'Geeks_for_for': 1, 'Geeks_for_geeks': 4, 'for_geeks_Geeks': 3, 'geeks_Geeks_for':
7}
final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks':
{'for': 7}}}
Time complexity: O(n), where n is the length of the key string.
Auxiliary space: O(N * n), where N is the number of items in the input dictionary and n is the length
of the longest key string.
Method #3: Using reduce and getitem
Python3
# Python code to demonstrate
# conversion of flattened dictionary
# into nested dictionary
from collections import defaultdict
from functools import reduce
from operator import getitem
def getFromDict(dataDict, mapList):
# Iterate nested dictionary
return reduce(getitem, mapList, dataDict)
# instantiate nested defaultdict of defaultdicts
tree = lambda: defaultdict(tree)
d = tree()
# converting default_dict_to regular dict
def default_to_regular(d):
"""Convert nested defaultdict to regular dict of dicts."""
if isinstance(d, defaultdict):
d = {k: default_to_regular(v) for k, v in d.items()}
return d
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
# printing initial dictionary
print ("initial_dictionary", str(ini_dict))
# code to convert ini_dict to nested dictionary
# iterating_over_dict
for k, v in ini_dict.items():
# splitting keys
* keys, final_key = k.split('_')
getFromDict(d, keys)[final_key] = v
# printing final dictionary
print ("final_dictionary", str(default_to_regular(d)))
Output
initial_dictionary {'Geeks_for_for': 1, 'Geeks_for_geeks': 4, 'for_geeks_Geeks': 3, 'geeks_Geeks_for':
7}
final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks':
{'for': 7}}}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(nm), where n and m are the same as explained above
Method 4 : Using a recursive function without defaultdict or reduce
uses a recursive function add_to_nested_dict to add values to a nested dictionary. The function
takes a nested dictionary, a list of keys, and a value as inputs. If the list of keys has only one key, the
function adds the value to the nested dictionary at that key. Otherwise, it creates a nested dictionary
at the first key if it doesn’t already exist, and then recursively calls the function with the remaining
keys and value.
step-by-step approach :
Create a function add_to_nested_dict that takes three arguments: a nested dictionary, a list of keys,
and a value. This function will add the value to the nested dictionary at the specified keys.
Check if the length of the keys list is 1. If it is, add the value to the nested dictionary at the last key in
the list.
If the length of the keys list is greater than 1, check if the first key is in the nested dictionary. If it
isn’t, create a new nested dictionary at that key.
Recursively call the add_to_nested_dict function with the nested dictionary at the first key in the list,
the remaining keys in the list, and the value.
Create an empty dictionary d that will hold the nested dictionary.
Iterate over the flattened dictionary ini_dict using a for loop.
Split each key in ini_dict into a list of keys using the split method.
Call the add_to_nested_dict function with the empty dictionary d, the list of keys, and the value.
Print the final nested dictionary d.
Python3
def add_to_nested_dict(nested_dict, keys, value):
"""Add a value to a nested dictionary at the specified keys."""
if len(keys) == 1:
# base case: add value to the last key in the list
nested_dict[keys[0]] = value
else:
# recursive case: create nested dictionary if it doesn't exist
if keys[0] not in nested_dict:
nested_dict[keys[0]] = {}
# recursively call function with remaining keys and value
add_to_nested_dict(nested_dict[keys[0]], keys[1:], value)
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
# printing initial dictionary
print ("initial_dictionary", str(ini_dict))
# create empty nested dictionary
d = {}
# iterating_over_dict
for k, v in ini_dict.items():
# splitting keys
keys = k.split('_')
# add value to nested dictionary
add_to_nested_dict(d, keys, v)
# printing final dictionary
print ("final_dictionary", str(d))
Output
initial_dictionary {'Geeks_for_for': 1, 'Geeks_for_geeks': 4, 'for_geeks_Geeks': 3, 'geeks_Geeks_for':
7}
final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks':
{'for': 7}}}
The time complexity of this approach is O(nm), where n is the number of keys in the flattened
dictionary and m is the maximum depth of the nested dictionary.
The auxiliary space is also O(nm), since the function creates nested dictionaries as needed.
Method 5: Using a loop to iterate through the list of keys
Create an empty dictionary.
Iterate through the items in the initial dictionary using a for loop.
Split the keys into a list using the split() method and store the value in a variable.
Create a variable temp that references the empty dictionary.
Iterate through the list of keys using a for loop.
If the key exists in temp, update temp to reference the value of that key.
If the key does not exist in temp, create a new key with an empty dictionary as its value and update
temp to reference that value.
When the loop through the keys is finished, set the final value of the last key in the list to be the
value from the initial dictionary.
Return the nested dictionary.
Python3
def add_to_nested_dict(nested_dict, keys, value):
"""Add a value to a nested dictionary at the specified keys."""
temp = nested_dict
for key in keys[:-1]:
temp = temp.setdefault(key, {})
temp[keys[-1]] = value
return nested_dict
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
# printing initial dictionary
print ("initial_dictionary", str(ini_dict))
# create empty nested dictionary
d = {}
# iterating_over_dict
for k, v in ini_dict.items():
# splitting keys
keys = k.split('_')
# add value to nested dictionary
add_to_nested_dict(d, keys, v)
# printing final dictionary
print ("final_dictionary", str(d))
Output
initial_dictionary {'Geeks_for_for': 1, 'Geeks_for_geeks': 4, 'for_geeks_Geeks': 3, 'geeks_Geeks_for':
7}
final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks':
{'for': 7}}}
Time complexity: O(n*m), where n is the number of items in the initial dictionary and m is the
maximum number of keys in a single item.
Auxiliary space: O(m), where m is the maximum number of keys in a single item.
Last Updated : 10 Apr, 2023
Similar Reads
1.Python | Convert nested dictionar
Why does a nested loop perform much faster than the flattened one?
aniketpr11051998
Read
Discuss
Courses
Practice
Python provides three ways for executing the loops. While all the ways provide similar basic
functionality, they differ in their syntax and condition checking time.
In this article, we will see why does a nested loop performs better than the flattened one. But first,
let’s see what is a nested loop and what is a flattened loop.4
A nested loop performs faster than a flattened one because it takes advantage of spatial locality,
which is the principle that data that is close to each other in memory is also likely to be close to each
other in time.
When a nested loop iterates through an array, it typically accesses elements that are close to each
other in memory. This allows the CPU to access data from memory more quickly because it can take
advantage of the CPU cache, which is a small amount of memory that is built into the CPU itself. This
can greatly reduce the number of times that the CPU has to access main memory, which is much
slower than the CPU cache.
On the other hand, a flattened loop iterates through the entire array, which may cause the CPU to
frequently access memory that is not currently in the cache. This increases the number of times the
CPU has to access main memory, which can slow down the loop considerably.
Additionally, In some architectures, accessing memory in a sequential manner allows to use
prefetching mechanism, that can predict next memory location and fetch it to CPU cache before it’s
actually needed, which can also improve performance.
Nested loops are the logical structure in computer programming and coding. In which one loop
statement is inside another loop statement.
Syntax:
for [iter_1] in [sequence_1]:
for [iter_2] in [sequence_2]:
# statements of inner loop
statements(iter_2)
# statements of outer loop
statements(iter_1)
Loops have the ability to iterate over the items of any sequence, such as a list or a string.
Syntax:
for [iter] in sequence:
statements(s)
When we run our python script, the operating system we are running on will assign a Process ID for
it. It can be interrupted by system calls and its priority can be changed over time. But the system is
not likely to take resources away from a process when we change memory address or values. When
we run flat for loop it is assigning much fewer variables than a nested loop. So we can say that a
nested loop utilizes resources more than a flat loop if they are available.
Example:
Python3
# import module
import time
# flattened loop
def loop(n):
for i in range(n**3):
pass
# nested loop
def nested(n):
for i in range(n):
for j in range(n):
for k in range(n):
pass
for i in range(10, 100, 10):
start = time.time()
loop(i)
print('For flattened loop:',time.time() - start)
start = time.time()
nested(i)
print('For nested loop:',time.time() - start)
print()
Output:
For flattened loop: 2.7894973754882812e-05
For nested loop: 4.9114227294921875e-05
For flattened loop: 0.0002155303955078125
For nested loop: 0.00024271011352539062
For flattened loop: 0.0007171630859375
For nested loop: 0.0007529258728027344
For flattened loop: 0.0016894340515136719
For nested loop: 0.0012614727020263672
For flattened loop: 0.0029077529907226562
For nested loop: 0.0022766590118408203
For flattened loop: 0.004510402679443359
For nested loop: 0.003597736358642578
For flattened loop: 0.007539272308349609
For nested loop: 0.0057599544525146484
For flattened loop: 0.01167440414428711
For nested loop: 0.008468151092529297
For flattened loop: 0.016645431518554688
For nested loop: 0.01381683349609375
Advantages and Disadvantages:
Advantages of nested loops:
They take advantage of spatial locality, which can greatly improve performance by reducing the
number of times the CPU has to access main memory.
They can be used to iterate over multi-dimensional arrays, which can make the code more readable
and easier to understand.
They allow for better data encapsulation and organization, as the different levels of the loop can
represent different aspects of the data.
Disadvantages of nested loops:
They can be more difficult to understand and debug than flattened loops, especially when there are
multiple levels of nesting.
They can be less efficient than flattened loops when the data is not organized in a multi-dimensional
structure.
They can consume more memory if the nested data structure is large, as it can take more memory to
store the nested elements.
It’s worth noting that in some cases, nested loops can be flattened using techniques like linearizing,
or using more advanced data structures like sparse
matrices to represent the data. It’s important to have a good understanding of the problem and the
data structure to choose the best approach, and it’s also
important to measure the performance of different solutions to select the best one.
Python | Convert nested dictionary into flattened dictionary
garg_ak0109
Read
Discuss
Courses
Practice
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, and calls the flatten_dict function recursively on the value of each key. It
concatenates the original key and the returned key from the recursive call with the separator, and
uses that as the new key in the flattened dictionary. It sets the value of the new key to the returned
value from the recursive call.
If the input dd is not a dictionary, the function creates a new dictionary with a single key-value pair,
where the key is the prefix argument (which is the path to the current value in the original nested
dictionary), and the value is the input dd itself.
The code then initializes a nested dictionary ini_dict with some sample data.
The code prints the initial dictionary ini_dict.
The code calls the flatten_dict function on the ini_dict dictionary and prints the resulting flattened
dictionary.
Python3
# Python code to demonstrate
# conversion of nested dictionary
# into flattened dictionary
# code to convert ini_dict to flattened dictionary
# default separator '_'
def flatten_dict(dd, separator ='_', prefix =''):
return { prefix + separator + k if prefix else k : v
for kk, vv in dd.items()
for k, v in flatten_dict(vv, separator, kk).items()
} if isinstance(dd, dict) else { prefix : dd }
# initialising_dictionary
ini_dict = {'geeks': {'Geeks': {'for': 7}},
'for': {'geeks': {'Geeks': 3}},
'Geeks': {'for': {'for': 1, 'geeks': 4}}}
# printing initial dictionary
print ("initial_dictionary", str(ini_dict))
# printing final dictionary
print ("final_dictionary", str(flatten_dict(ini_dict)))
Output:
initial_dictionary {‘geeks’: {‘Geeks’: {‘for’: 7}}, ‘Geeks’: {‘for’: {‘geeks’: 4, ‘for’: 1}}, ‘for’: {‘geeks’:
{‘Geeks’: 3}}}
final_dictionary {‘Geeks_for_for’: 1, ‘geeks_Geeks_for’: 7, ‘for_geeks_Geeks’: 3, ‘Geeks_for_geeks’:
4}
Time complexity: O(n^2), where n is the total number of keys in the nested dictionary.
Auxiliary space: O(n), where n is the total number of keys in the nested dictionary. The auxiliary
space is used to store the result of the flatten dictionary in the form of a new dictionary.
Method #2: Using mutableMapping
Python3
# Python code to demonstrate
# conversion of nested dictionary
# into flattened dictionary
from collections import MutableMapping
# code to convert ini_dict to flattened dictionary
# default separator '_'
def convert_flatten(d, parent_key ='', sep ='_'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, MutableMapping):
items.extend(convert_flatten(v, new_key, sep = sep).items())
else:
items.append((new_key, v))
return dict(items)
# initialising_dictionary
ini_dict = {'geeks': {'Geeks': {'for': 7}},
'for': {'geeks': {'Geeks': 3}},
'Geeks': {'for': {'for': 1, 'geeks': 4}}}
# printing initial dictionary
print ("initial_dictionary", str(ini_dict))
# printing final dictionary
print ("final_dictionary", str(convert_flatten(ini_dict)))
# Python code to demonstrate
# conversion of nested dictionary
# into flattened dictionary
my_map = {"a" : 1,
"b" : {
"c": 2,
"d": 3,
"e": {
"f":4,
6:"a",
5:{"g" : 6},
"l":[1,"two"]
}
}}
# Expected Output
# {'a': 1, 'b_c': 2, 'b_d': 3, 'b_e_f': 4, 'b_e_6': 'a', 'b_e_5_g': 6, 'b_e_l': [1, 'two']}
ini_dict = {'geeks': {'Geeks': {'for': 7}},
'for': {'geeks': {'Geeks': 3}},
'Geeks': {'for': {'for': 1, 'geeks': 4}}}
# Expected Output
# {‘Geeks_for_geeks’: 4, ‘for_geeks_Geeks’: 3, ‘Geeks_for_for’: 1, ‘geeks_Geeks_for’: 7}
def flatten_dict(pyobj, keystring=''):
if type(pyobj) == dict:
keystring = keystring + '_' if keystring else keystring
for k in pyobj:
yield from flatten_dict(pyobj[k], keystring + str(k))
else:
yield keystring, pyobj
print("Input : %s\nOutput : %s\n\n" %
(my_map, { k:v for k,v in flatten_dict(my_map) }))
print("Input : %s\nOutput : %s\n\n" %
(ini_dict, { k:v for k,v in flatten_dict(ini_dict) }))
Output:
initial_dictionary {‘for’: {‘geeks’: {‘Geeks’: 3}}, ‘geeks’: {‘Geeks’: {‘for’: 7}}, ‘Geeks’: {‘for’: {‘for’: 1,
‘geeks’: 4}}}
final_dictionary {‘Geeks_for_geeks’: 4, ‘for_geeks_Geeks’: 3, ‘Geeks_for_for’: 1, ‘geeks_Geeks_for’:
7}
Time complexity: O(n), where n is the total number of keys in the nested dictionary
Auxiliary space: O(n), where n is the total number of keys in the nested dictionary.
Method #4: Using recursion and a separator
Define a function “flatten_dict” that takes in three parameters: dd (a dictionary), separator (a string,
default value “_”), and prefix (a string, default value “”).
Initialize an empty dictionary “res”.
Iterate through each key-value pair in the dictionary “dd”.
Check if the value associated with the current key is itself a dictionary or not. If it is a dictionary, then
recursively call the “flatten_dict” function with the value as the new dictionary to be flattened, the
separator and prefix updated with the current key and separator value.
If the value is not a dictionary, then add the key-value pair to the “res” dictionary, where the key is
the concatenation of prefix, separator and current key.
Return the final “res” dictionary.
Python3
# code to convert ini_dict to flattened dictionary
def flatten_dict(dd, separator='_', prefix=''):
res = {}
for key, value in dd.items():
if isinstance(value, dict):
res.update(flatten_dict(value, separator, prefix + key + separator))
else:
res[prefix + key] = value
return res
# initialising_dictionary
ini_dict = {'geeks': {'Geeks': {'for': 7}},
'for': {'geeks': {'Geeks': 3}},
'Geeks': {'for': {'for': 1, 'geeks': 4}}}
# printing initial dictionary
print("initial dictionary", str(ini_dict))
# flattening the dictionary
res = flatten_dict(ini_dict)
# printing final dictionary
print("final dictionary", str(res))
#This code is contributed by Vinay Pinjala.
Python | Convert flattened dictionary into nested dictionary
garg_ak0109
Read
Discuss
Courses
Practice
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
function iterates over all elements of the input list except the last two elements, and creates nested
dictionaries corresponding to each element in the list.
The insert() function then updates the dictionary (dct) with a key-value pair where the key is the
second last element of the input list, and the value is the last element of the input list.
Define a function named convert_nested that takes a dictionary (dct) as an input. This function first
initializes an empty dictionary named result to store the output nested dictionary.
The function then creates an iterator named lists, which is a list of lists where each list represents a
hierarchical flow of keys and values from the input dictionary. To create this iterator, it splits each
key of the input dictionary by the ‘_’ character and appends the corresponding value to the list.
The convert_nested() function then iterates over each list in the lists iterator and inserts it into the
result dictionary using the insert() function.
Finally, the convert_nested() function returns the resulting nested dictionary result.
Define an initial dictionary named ini_dict containing key-value pairs.
Print the initial dictionary using the print() function.
Create a new list named _split_dict that contains lists representing the hierarchical flow of keys and
values from the initial dictionary by splitting each key of the dictionary by the ‘_’ character and
appending the corresponding value to the list.
Print the final nested dictionary by calling the convert_nested() function on the initial dictionary and
print the resulting nested dictionary using the print() function.
Below is the implementation of the above approach:
Python3
# Python code to demonstrate
# conversion of flattened dictionary
# into nested dictionary
def insert(dct, lst):
for x in lst[:-2]:
dct[x] = dct = dct.get(x, dict())
dct.update({lst[-2]: lst[-1]})
def convert_nested(dct):
# empty dict to store the result
result = dict()
# create an iterator of lists
# representing nested or hierarchical flow
lists = ([*k.split("_"), v] for k, v in dct.items())
# insert each list into the result
for lst in lists:
insert(result, lst)
return result
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
# printing initial dictionary
print ("initial_dictionary", str(ini_dict))
# code to convert ini_dict to nested
# dictionary splitting_dict_keys
_split_dict = [[*a.split('_'), b] for a, b in ini_dict.items()]
# printing final dictionary
print ("final_dictionary", str(convert_nested(ini_dict)))
Output
initial_dictionary {'Geeks_for_for': 1, 'Geeks_for_geeks': 4, 'for_geeks_Geeks': 3, 'geeks_Geeks_for':
7}
final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks':
{'for': 7}}}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using default dict and recursive approach
Python3
# Python code to demonstrate
# conversion of flattened dictionary
# into nested dictionary
# code to convert dict into nested dict
def nest_dict(dict1):
result = {}
for k, v in dict1.items():
# for each key call method split_rec which
# will split keys to form recursively
# nested dictionary
split_rec(k, v, result)
return result
def split_rec(k, v, out):
# splitting keys in dict
# calling_recursively to break items on '_'
k, *rest = k.split('_', 1)
if rest:
split_rec(rest[0], v, out.setdefault(k, {}))
else:
out[k] = v
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
# printing initial dictionary
print ("initial_dictionary", str(ini_dict))
# printing final dictionary
print ("final_dictionary", str(nest_dict(ini_dict)))
Output
initial_dictionary {'Geeks_for_for': 1, 'Geeks_for_geeks': 4, 'for_geeks_Geeks': 3, 'geeks_Geeks_for':
7}
final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks':
{'for': 7}}}
Time complexity: O(n), where n is the length of the key string.
Auxiliary space: O(N * n), where N is the number of items in the input dictionary and n is the length
of the longest key string.
Method #3: Using reduce and getitem
Python3
# Python code to demonstrate
# conversion of flattened dictionary
# into nested dictionary
from collections import defaultdict
from functools import reduce
from operator import getitem
def getFromDict(dataDict, mapList):
# Iterate nested dictionary
return reduce(getitem, mapList, dataDict)
# instantiate nested defaultdict of defaultdicts
tree = lambda: defaultdict(tree)
d = tree()
# converting default_dict_to regular dict
def default_to_regular(d):
"""Convert nested defaultdict to regular dict of dicts."""
if isinstance(d, defaultdict):
d = {k: default_to_regular(v) for k, v in d.items()}
return d
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
# printing initial dictionary
print ("initial_dictionary", str(ini_dict))
# code to convert ini_dict to nested dictionary
# iterating_over_dict
for k, v in ini_dict.items():
# splitting keys
* keys, final_key = k.split('_')
getFromDict(d, keys)[final_key] = v
# printing final dictionary
print ("final_dictionary", str(default_to_regular(d)))
Output
initial_dictionary {'Geeks_for_for': 1, 'Geeks_for_geeks': 4, 'for_geeks_Geeks': 3, 'geeks_Geeks_for':
7}
final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks':
{'for': 7}}}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(nm), where n and m are the same as explained above
Method 4 : Using a recursive function without defaultdict or reduce
uses a recursive function add_to_nested_dict to add values to a nested dictionary. The function
takes a nested dictionary, a list of keys, and a value as inputs. If the list of keys has only one key, the
function adds the value to the nested dictionary at that key. Otherwise, it creates a nested dictionary
at the first key if it doesn’t already exist, and then recursively calls the function with the remaining
keys and value.
step-by-step approach :
Create a function add_to_nested_dict that takes three arguments: a nested dictionary, a list of keys,
and a value. This function will add the value to the nested dictionary at the specified keys.
Check if the length of the keys list is 1. If it is, add the value to the nested dictionary at the last key in
the list.
If the length of the keys list is greater than 1, check if the first key is in the nested dictionary. If it
isn’t, create a new nested dictionary at that key.
Recursively call the add_to_nested_dict function with the nested dictionary at the first key in the list,
the remaining keys in the list, and the value.
Create an empty dictionary d that will hold the nested dictionary.
Iterate over the flattened dictionary ini_dict using a for loop.
Split each key in ini_dict into a list of keys using the split method.
Call the add_to_nested_dict function with the empty dictionary d, the list of keys, and the value.
Print the final nested dictionary d.
Python3
def add_to_nested_dict(nested_dict, keys, value):
"""Add a value to a nested dictionary at the specified keys."""
if len(keys) == 1:
# base case: add value to the last key in the list
nested_dict[keys[0]] = value
else:
# recursive case: create nested dictionary if it doesn't exist
if keys[0] not in nested_dict:
nested_dict[keys[0]] = {}
# recursively call function with remaining keys and value
add_to_nested_dict(nested_dict[keys[0]], keys[1:], value)
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
# printing initial dictionary
print ("initial_dictionary", str(ini_dict))
# create empty nested dictionary
d = {}
# iterating_over_dict
for k, v in ini_dict.items():
# splitting keys
keys = k.split('_')
# add value to nested dictionary
add_to_nested_dict(d, keys, v)
# printing final dictionary
print ("final_dictionary", str(d))
Python | Pretty Print a dictionary with dictionary value
manjeet_04
Read
Discuss
Courses
Practice
This article just provides a quick way to pretty print a dictionary that has dictionary as values. This is
required many times nowadays as the advent of NoSQL databases. Let’s code a way to perform this
particular task.
Method 1: Using loops We just loop through each dictionary element and its corresponding values
using brute manner of loops.
Step-by-step approach :
Create a dictionary with nested dictionaries as values.
Print the original dictionary.
Loop through the top-level keys of the dictionary.
For each top-level key, print it.
Loop through the keys of the nested dictionary associated with the top-level key.
For each key in the nested dictionary, print the key-value pair in the format “key: value”.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Pretty Print a dictionary with dictionary value
# Using loops
# initializing dictionary
test_dict = {'gfg': {'rate': 5, 'remark': 'good'}, 'cs': {'rate': 3}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using loops to Pretty Print
print("The Pretty Print dictionary is : ")
for sub in test_dict:
print(sub)
for sub_nest in test_dict[sub]:
print(sub_nest, ':', test_dict[sub][sub_nest])
Output :
The original dictionary is : {'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}}
The Pretty Print dictionary is :
gfg
remark : good
rate : 5
cs
rate : 3
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 2: Using the built-in json module
STEPS:
First, the program imports the json module to use its dumps() function for pretty printing
dictionaries.
The program initializes a nested dictionary called test_dict with two keys: gfg and cs.
The gfg key has two nested key-value pairs, rate and remark, with values of 5 and ‘good’,
respectively.
The cs key has only one nested key-value pair, rate, with a value of 3.
The program prints the original dictionary using the print() function and the test_dict variable.
The program uses the dumps() function from the json module to pretty print the test_dict dictionary.
The pretty printed dictionary is assigned to a new variable called pretty_dict.
Finally, the program prints the pretty printed dictionary using the print() function and the pretty_dict
variable. The indent argument is set to 4 to make the output more readable.
Python3
import json
# initializing dictionary
test_dict = {'gfg': {'rate': 5, 'remark': 'good'}, 'cs': {'rate': 3}}
# printing original dictionary
print("The original dictionary is : ", test_dict)
# using json.dumps() to Pretty Print
pretty_dict = json.dumps(test_dict, indent=4)
print("The Pretty Print dictionary is : \n", pretty_dict)
Output
The original dictionary is : {'gfg': {'rate': 5, 'remark': 'good'}, 'cs': {'rate': 3}}
The Pretty Print dictionary is :
"gfg": {
"rate": 5,
"remark": "good"
},
"cs": {
"rate": 3
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 3:Using recursion and string concatenation:
1. The function starts by initializing an empty string, res.
2. Then it loops over each item in the input dictionary d by calling the items method. This operation
takes O(N) time where N is the number of items in the dictionary.
3. Inside the loop, the function appends a string to res using the += operator. The length of the string
being appended is proportional to the 4.current value of indent and the length of the key and value
being printed. Assuming the maximum length of key and value to be M, the time 5.complexity of
each iteration of the loop is O(indent + M).
6.If the current value is a dictionary, the function calls itself recursively with the inner dictionary and
an incremented value of indent. The recursive 7.call will have to traverse through all the items in the
nested dictionary. Therefore, the time complexity of the recursive call is O(M*k) where k is the
number of items in the nested dictionary.
8.Finally, the function returns the resulting string res.
Python3
def pretty_print_dict(d, indent=0):
res = ""
for k, v in d.items():
res += "\t"*indent + str(k) + "\n"
if isinstance(v, dict):
res += pretty_print_dict(v, indent+1)
else:
res += "\t"*(indent+1) + str(v) + "\n"
return res
test_dict = {'gfg': {'rate': 5, 'remark': 'good'}, 'cs': {'rate': 3}}
# Using recursion and string concatenation for Pretty Print
print("The Pretty Print dictionary is : ")
print(pretty_print_dict(test_dict))
# This code is contributed by Jyothi pinjala.
Output
The Pretty Print dictionary is :
gfg
rate
remark
good
cs
rate
3
The time complexity: O(N), where N is the total number of elements in the dictionary, since it
iterates through each element once.
The auxiliary space: O(N), since it stores the output string in memory, and the size of the output
string is proportional to the size of the dictionary. Additionally, the recursive calls to
pretty_print_dict also use stack space, which could potentially grow to O(N) in the worst case
scenario where the dictionary is deeply nested.
Method 4: Using for loop+dictionary
Approach
for loop to iterate over the keys and values of the dictionary.
Algorithm
Initialize an empty string to hold the pretty-printed dictionary.
Iterate over the keys and values of the dictionary using a for loop.
For each key-value pair, add the key to the string followed by a colon and a space.
For each value, add it to the string followed by a newline character.
Return the pretty-printed dictionary string.
Python3
def pretty_print_dict(d):#define d
pretty_dict = '' #take empty string
for k, v in d.items():#get items for dict
pretty_dict += f'{k}: \n'
for value in v:
pretty_dict += f' {value}: {v[value]}\n'
return pretty_dict#return result
d = {'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}}#input
print(pretty_print_dict(d))#print output
Output
gfg:
remark: good
rate: 5
cs:
rate: 3
Time Complexity: O(n^2), where n is the number of key-value pairs in the dictionary.
Auxiliary Space: O(n), where n is the number of key-value pairs in the dictionary
Method 5: Using the pprint module
The pprint module is a built-in module in Python that provides a way to pretty-print arbitrary Python
data structures in a form that can be used as input to the interpreter. It is useful for debugging and
displaying complex structures.
Python3
# import the pprint module
import pprint
# initialize the dictionary
test_dict = {'gfg' : {'rate' : 5, 'remark' : 'good'}, 'cs' : {'rate' : 3}}
# pretty-print the dictionary
print("The pretty-printed dictionary is:")
pprint.pprint(test_dict)
Output
The pretty-printed dictionary is:
{'cs': {'rate': 3}, 'gfg': {'rate': 5, 'remark': 'good'}}
The time complexity of the pprint module function pprint() depends on the size of the input
dictionary.
The space complexity of the pprint module function pprint() is also dependent on the size of the
input dictionary.
Method 6: using the json.dumps() method with an argument indent.
Step-by-step approach:
Import the json module.
Initialize the dictionary.
Print the original dictionary.
Use json.dumps() method with indent argument to pretty print the dictionary.
Print the pretty printed dictionary.
Below is the implementation of the above approach:
Python3
# Importing json module
import json
# Initializing dictionary
test_dict = {'gfg' : {'rate' : 5, 'remark' : 'good'}, 'cs' : {'rate' : 3}}
# Printing original dictionary
print("The original dictionary is : ", test_dict)
# Using json.dumps() with indent argument to Pretty Print
print("The Pretty Print dictionary is : ")
pretty_print_dict = json.dumps(test_dict, indent=4)
print(pretty_print_dict)
Regular Dictionary vs Ordered Dictionary in Python
AlapanKar
Read
Discuss
Courses
Practice
Dictionary in Python is an unordered collection of data values, used to store data values like a map,
which unlike other Data Types that hold only single value as an element, Dictionary holds key:value
pair. Key-value is provided in the dictionary to make it more optimized. A regular dictionary type
does not track the insertion order of the (key, value) pairs and thus iterates through the keys based
on how they are stored in the hash table which in turn is based on random values so as to reduce
collisions.
In contrast to this Python provides the OrderedDict type which remembers the insertion order of
(key, value) pairs in the dictionary and thus preserves the order. OrderedDict consumes more
memory than a regular dictionary in Python because of the underlying Doubly LinkedList
implementation to preserving the order.
Example:
Python
# A Python program to demonstrate
# the difference between regular
# and ordered dictionary.
import collections
# Creating a regular dictionary
print('Regular dictionary:')
d = {chr(k):k for k in range(ord('a'), ord('g'))}
for k, v in d.items():
print(k, v)
# Creating an Ordered dictionary
print('\nOrderedDict:')
d = collections.OrderedDict()
[d.setdefault(chr(k), k) for k in range(ord('a'), ord('g'))]
for k, v in d.items():
print(k, v)
Output :
Regular dictionary:
('a', 97)
('c', 99)
('b', 98)
('e', 101)
('d', 100)
('f', 102)
OrderedDict:
('a', 97)
('b', 98)
('c', 99)
('d', 100)
('e', 101)
('f', 102)
The time complexity of this program is O(N), where N is the number of key-value pairs in the
dictionary.
The auxiliary space complexity of this program is O(N), because it stores N key-value pairs in the
regular dictionary and in the OrderedDict.
Note: Starting from Python 3.7, insertion order of Python dictionaries is guaranteed.
Deletion and Re-Inserting:
Deleting and re-inserting the same key will push it to the back as OrderedDict however maintains the
order of insertion.
Example:
Python
# A Python program to demonstrate
# working of deletion and re-insertion in
# regular and OrderedDict
from collections import OrderedDict
print("Before deleting:\n")
d = {}
print("Regular dictionary:")
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
for key, value in d.items():
print(key, value)
od = OrderedDict()
print("\nOrdered dictionary:")
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
for key, value in od.items():
print(key, value)
print("\nAfter deleting:\n")
print("Regular dictionary:")
d.pop('c')
for key, value in d.items():
print(key, value)
print("\nOrdered dictionary:")
od.pop('c')
for key, value in od.items():
print(key, value)
print("\nAfter re-inserting:\n")
print("Regular dictionary:")
d['c'] = 3
for key, value in d.items():
print(key, value)
print("\nOrdered dictionary:")
od['c'] = 3
for key, value in od.items():
print(key, value)
Output:
Before deleting:
Regular dictionary:
('a', 1)
('c', 3)
('b', 2)
('d', 4)
Ordered dictionary:
('a', 1)
('b', 2)
('c', 3)
('d', 4)
After deleting:
Regular dictionary:
('a', 1)
('b', 2)
('d', 4)
Ordered dictionary:
('a', 1)
('b', 2)
('d', 4)
After re-inserting:
Regular dictionary:
('a', 1)
('c', 3)
('b', 2)
('d', 4)
Ordered dictionary:
('a', 1)
('b', 2)
('d', 4)
('c', 3)
The time complexity is O(n), as each element needs to be inserted into the dictionary.
The space complexity of re-inserting an element into a dictionary is O(1), as it only involves adding
one element to the dictionary.
Python | Dictionary initialization with common dictionary
manjeet_04
Read
Discuss
Courses
Practice
Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a
dictionary with records values, so that they can be altered later. This kind of application can occur in
cases of memoizations in general or competitive programming. Let’s discuss certain way in which
this task can be performed.
Method 1: Using zip() + repeat() The combination of these functions can be used to perform this
particular task. In this, the Dictionary value is attached to the keys repeated using the repeat() by
help of zip()
Step-by-step approach :
Import the repeat function from the itertools module.
Initialize a dictionary test_dict with key-value pairs.
Call the zip() function with two arguments:
a. The range() function to create a sequence of numbers from 0 to 3 (inclusive).
b. The repeat() function with the test_dict dictionary as its argument to create an iterable that
returns test_dict infinitely.
Pass the output of zip() to the dict() function to create a dictionary from the key-value pairs
generated by zip().
Assign the resulting dictionary to the variable res.
Print the resulting dictionary res.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Dictionary initialization with common dictionary
# Using zip() + repeat()
from itertools import repeat
# initialization Dictionary
test_dict = {'gfg' : 1, 'best' : 3}
# Using zip() + repeat()
# Dictionary initialization with common dictionary
res = dict(zip(range(4), repeat(test_dict)))
# printing result
print("The dictionary with record values : " + str(res))
Output
The dictionary with record values : {0: {'gfg': 1, 'best': 3}, 1: {'gfg': 1, 'best': 3}, 2: {'gfg': 1, 'best': 3}, 3:
{'gfg': 1, 'best': 3}}
Time complexity: O(1)
Auxiliary space: O(1)
Method 2: Using dict.fromkeys()
Step-by-step approach:
Uses the ‘dict.fromkeys()’ method to initialize a new dictionary named ‘res’. The ‘range(4)’ function
creates a sequence of numbers from 0 to 3, and the ‘test_dict’ dictionary is passed as the second
argument to the ‘dict.fromkeys()’ method. This creates a new dictionary where each key in the range
sequence maps to the same value (which is the entire ‘test_dict’ dictionary).
Finally, prints the resulting dictionary using the ‘print()’ function. The resulting dictionary is stored in
the ‘res’ variable, and it contains 4 key-value pairs, where each key is a number from 0 to 3, and
each value is the same dictionary as ‘test_dict’.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Dictionary initialization with common dictionary
# Using dict.fromkeys()
# initialization Dictionary
test_dict = {'gfg' : 1, 'best' : 3}
# Using dict.fromkeys()
# Dictionary initialization with common dictionary
res = dict.fromkeys(range(4), test_dict)
# printing result
print("The dictionary with record values : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
Output
The dictionary with record values : {0: {'gfg': 1, 'best': 3}, 1: {'gfg': 1, 'best': 3}, 2: {'gfg': 1, 'best': 3}, 3:
{'gfg': 1, 'best': 3}}
Time Complexity : O(n)
Auxiliary Space : O(n)
Method #3: Using a dictionary comprehension.
Initializes a dictionary named ‘test_dict’ with two key-value pairs. It then creates a new dictionary
‘res’ with keys ranging from 0 to 3, and assigns the same dictionary object ‘test_dict’ as the value for
each key. Finally, it prints the resulting dictionary ‘res’.
Python3
test_dict = {'gfg': 1, 'best': 3}
res = {key: test_dict for key in range(4)}
print("The dictionary with record values : " + str(res))
Output
The dictionary with record values : {0: {'gfg': 1, 'best': 3}, 1: {'gfg': 1, 'best': 3}, 2: {'gfg': 1, 'best': 3}, 3:
{'gfg': 1, 'best': 3}}
Python – Update dictionary with other dictionary
manjeet_04
Read
Discuss
Courses
Practice
Sometimes, while working with Python dictionaries, we can have problem in which we need to
perform the update of dictionary with other keys of dictionary. This can have applications in domains
in which we need to add certain records to previously captured records. Let’s discuss certain ways in
which this task can be performed.
Method #1 : Using loop This is a brute force way in which this task can be performed. In this, we
check for keys in other dictionary, and add the items in new dictionary.
Python3
# Python3 code to demonstrate working of
# Update dictionary with other dictionary
# Using loop
# initializing dictionaries
test_dict1 = {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
test_dict2 = {'for': 3, 'geeks': 5}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# Update dictionary with other dictionary
# Using loop
for key in test_dict1:
if key in test_dict2:
test_dict1[key] = test_dict2[key]
# printing result
print("The updated dictionary is : " + str(test_dict1))
Output :
The original dictionary 1 is : {‘best’: 2, ‘for’: 4, ‘gfg’: 1, ‘geeks’: 6} The original dictionary 2 is : {‘for’: 3,
‘geeks’: 5} The updated dictionary is : {‘best’: 2, ‘for’: 3, ‘gfg’: 1, ‘geeks’: 5}
Method #2 : Using dictionary comprehension This is yet another way in which this task can be
performed. In this, we iterate for dictionary and perform update in single line using comprehension.
Python3
# Python3 code to demonstrate working of
# Update dictionary with other dictionary
# Using dictionary comprehension
# initializing dictionaries
test_dict1 = {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
test_dict2 = {'for': 3, 'geeks': 5}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# Update dictionary with other dictionary
# Using dictionary comprehension
res = {key: test_dict2.get(key, val) for key, val in test_dict1.items()}
# printing result
print("The updated dictionary is : " + str(res))
Output :
The original dictionary 1 is : {‘best’: 2, ‘for’: 4, ‘gfg’: 1, ‘geeks’: 6} The original dictionary 2 is : {‘for’: 3,
‘geeks’: 5} The updated dictionary is : {‘best’: 2, ‘for’: 3, ‘gfg’: 1, ‘geeks’: 5}
The time complexity of the given program is O(N), where N is the total number of keys in both the
dictionaries.
The space complexity of the program is also O(N), where N is the number of keys in test_dict1.
Method #3 : Using update() method
Python3
# Python3 code to demonstrate working of
# Update dictionary with other dictionary
# Using loop
# initializing dictionaries
test_dict1 = {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
test_dict2 = {'for': 3, 'geeks': 5}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# Update dictionary with other dictionary
# Using loop
test_dict1.update(test_dict2)
# printing result
print("The updated dictionary is : " + str(test_dict1))
Output
The original dictionary 1 is : {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
The original dictionary 2 is : {'for': 3, 'geeks': 5}
The updated dictionary is : {'gfg': 1, 'best': 2, 'for': 3, 'geeks': 5}
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #4: Using the’ **’ operator: The ‘**’ operator
Define the two dictionaries:
Print the original dictionaries to verify their contents:
Use the “**” operator to combine the dictionaries into a new dictionary:
Print the updated dictionary to verify the combination:
The output should show the updated dictionary with the combined key-value pairs:
Example:
Python3
# Define the two dictionaries
test_dict1 = {'gfg' : 1, 'best' : 2, 'for' : 4, 'geeks' : 6}
test_dict2 = {'for' : 3, 'geeks' : 5}
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# Use the "**" operator to combine the dictionaries
# The "**" operator is used to unpack dictionaries and pass the key-value pairs as separate
arguments to a function
# In this case, we are using the "**" operator to unpack the dictionaries and add their key-value
pairs to a new dictionary
test_dict1 = {**test_dict1, **test_dict2}
# Print the combined dictionary
print("The updated dictionary is : " + str(test_dict1))
# Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Output
The original dictionary 1 is : {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
The original dictionary 2 is : {'for': 3, 'geeks': 5}
The updated dictionary is : {'gfg': 1, 'best': 2, 'for': 3, 'geeks': 5}
Time Complexity: Creating the DataFrame object takes O(n) time, where n is the length of the first
list.
Extracting the values from the first list corresponding to the indices in the second list using the loc[]
function takes O(m) time, where m is the length of the second list.
Converting the resulting series object to a list takes O(m) time.
Therefore, the overall time complexity of the algorithm is O(n+m).
Auxiliary Space Complexity: The algorithm uses O(n) auxiliary space to store the DataFrame object
and O(m) auxiliary space to store the resulting list. Therefore, the overall auxiliary space complexity
of the algorithm is O(n+m). Note that this assumes that the length of the resulting list is at most
min(n,m); if the length of the resulting list can be greater than min(n,m), then the overall auxiliary
space complexity would be O(max(n,m)).
Method #6: Using the dict() constructor and the update() method
Use the dict() constructor to create a copy of the first dictionary and then updates it with the second
dictionary using the update() method.
Python3
# Python3 code to demonstrate working of
# Update dictionary with other dictionary
# Using the dict() constructor and update() method
# initializing dictionaries
test_dict1 = {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
test_dict2 = {'for': 3, 'geeks': 5}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# Update dictionary with other dictionary
# Using the dict() constructor and update() method
new_dict = dict(test_dict1)
new_dict.update(test_dict2)
# printing result
print("The updated dictionary is : " + str(new_dict))
Output
The original dictionary 1 is : {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
The original dictionary 2 is : {'for': 3, 'geeks': 5}
The updated dictionary is : {'gfg': 1, 'best': 2, 'for': 3, 'geeks': 5}
Time complexity: O(N), where N is the total number of key-value pairs in both dictionaries.
Auxiliary space: O(N)
Method #7: Using reduce():
Import the reduce() function from the functools module.
Initialize the two dictionaries to be merged.
Define a lambda function that takes two arguments: an accumulator dictionary and the next
dictionary to merge, and returns a new dictionary that is the result of merging the accumulator
dictionary with the next dictionary using the unpacking syntax **.
Use the reduce() function to apply the lambda function to each dictionary in the list of dictionaries to
be merged, starting with the first dictionary as the initial accumulator value.
Return the final merged dictionary.
Python3
from functools import reduce
# initializing dictionaries
test_dict1 = {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
test_dict2 = {'for': 3, 'geeks': 5}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# Update dictionary with other dictionary using reduce
updated_dict = reduce(lambda acc, d: {**acc, **d}, [test_dict1, test_dict2])
# printing result
print("The updated dictionary is : " + str(updated_dict))
#This code is contributed by Jyothi pinjala.
Python – Filter dictionary values in heterogeneous dictionary
manjeet_04
Read
Discuss
Courses
Practice
Sometimes, while working with Python dictionaries, we can have a problem in which we need to
filter out certain values based on certain conditions on a particular type, e.g all values smaller than K.
This task becomes complex when dictionary values can be heterogeneous. This kind of problem can
have applications across many domains. Let’s discuss certain ways in which this task can be
performed.
Input : test_dict = {‘Gfg’ : 10, ‘for’ : ‘geeks’}
Output : {‘Gfg’: 10, ‘for’: ‘geeks’}
Input : test_dict = {‘Gfg’ : ‘geeks’}
Output : {‘Gfg’: ‘geeks’}
Method #1 : Using type() + dictionary comprehension
The combination of above functions can be used to perform this task. In this, we check for integral
type using type() and filter the data in dictionary comprehension.
Step-by-step approach
Use dictionary comprehension to create a new dictionary res.
Iterate over the items of test_dict using the items() method.
For each item, check if the value is not an integer (type(val) != int) or if it is greater than K (val > K).
If the condition is true, add the key-value pair to the new dictionary res.
Print the new dictionary res using the print() function.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using type() + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K=3
# Filter dictionary values in heterogeneous dictionary
# Using type() + dictionary comprehension
res = {key : val for key, val in test_dict.items()
if type(val) != int or val > K}
# printing result
print("Values greater than K : " + str(res))
Output :
The original dictionary : {'Gfg': 4, 'for': 'geeks', 'is': 2, 'best': 3}
Values greater than K : {'Gfg': 4, 'for': 'geeks'}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using isinstance() + dictionary comprehension
The combination of above functions can also be used to solve this problem. In this, we perform this
task similar to above, but the difference being that type test is done by isinstance() rather than
type().
Python3
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using isinstance() + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K=3
# Filter dictionary values in heterogeneous dictionary
# Using isinstance() + dictionary comprehension
res = {key : val for key, val in test_dict.items()
if not isinstance(val, int) or val > K}
# printing result
print("Values greater than K : " + str(res))
Output :
The original dictionary : {'Gfg': 4, 'for': 'geeks', 'is': 2, 'best': 3}
Values greater than K : {'Gfg': 4, 'for': 'geeks'}
Time complexity: O(n), where n is the number of items in the dictionary.
Auxiliary space: O(k), where k is the number of items in the resulting dictionary after filtering.
Method 3: Using a for loop and conditional statements:
Step-by-step approach:
Initialize a dictionary test_dict with some key-value pairs.
Print the original dictionary using print(“The original dictionary : ” + str(test_dict)).
Initialize an integer K with value 3.
Create an empty dictionary res to store the filtered values.
Loop through the key-value pairs of the dictionary using for key, val in test_dict.items()
Use a conditional statement to filter the dictionary values. If the value is not an integer or it is
greater than K, we add it to the res dictionary using res[key] = val.
Print the filtered dictionary using print(“Values greater than K : ” + str(res)).
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using for loop and conditional statements
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K=3
# Filter dictionary values in heterogeneous dictionary
# Using for loop and conditional statements
res = {}
for key, val in test_dict.items():
if type(val) != int or val > K:
res[key] = val
# printing result
print("Values greater than K : " + str(res))
Output
The original dictionary : {'Gfg': 4, 'is': 2, 'best': 3, 'for': 'geeks'}
Values greater than K : {'Gfg': 4, 'for': 'geeks'}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary.
Method #4: Using a dictionary comprehension with if condition:
Step-by-step approach:
Initialize a dictionary test_dict with some key-value pairs.
Initialize a variable K with a value to compare against dictionary values.
Use dictionary comprehension to filter out the items from the dictionary.
Loop through each key-value pair in the dictionary and check if the value is either non-integer or
greater than K.
If the value satisfies the condition, add the key-value pair to the result dictionary.
Return the filtered dictionary.
Below is the implementation of the above approach:
Python3
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# initializing K
K=3
# Filter dictionary values in heterogeneous dictionary
# Using dictionary comprehension with if condition
res = {k:v for k, v in test_dict.items() if type(v) != int or v > K}
# printing result
print("Values greater than K : " + str(res))
Output
Values greater than K : {'Gfg': 4, 'for': 'geeks'}
Time complexity: O(n) as it loops through all the items in the dictionary once.
Auxiliary space: O(n) as it creates a new dictionary to store the filtered items.
Method #6: Using filter() function with lambda function
Step-by-step approach:
Initialize a variable K with a value of 3.
Use the filter() function to filter the items in the test_dict dictionary using a lambda function. The
lambda function checks if an item’s value is not an integer or is greater than K.
Convert the filtered items into a dictionary using the dict() function.
Assign the filtered dictionary to a variable named res.
Print the filtered dictionary using the print() function.
Below is the implementation of the above approach:
Python3
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K=3
# Filter dictionary values in heterogeneous dictionary
# Using filter() function with lambda function
res = dict(filter(lambda item: not(isinstance(item[1], int) and item[1] <= K), test_dict.items()))
# printing result
print("Values greater than K : " + str(res))
Python | Filter dictionary key based on the values in selective list
manjeet_04
Read
Discuss
Courses
Practice
In Python, sometimes we require to get only some of the dictionary keys and not all. This problem is
quite common in web development we require to get only the selective dictionary keys from some
given list. Let’s discuss certain ways in which this problem can be solved.
Method #1: Using list comprehension
The list comprehension can be used to solve this particular problem. This is just the shorthand way
of performing it instead of writing a loop.
Python3
# Python3 code to demonstrate
# getting selective dictionary keys
# using list comprehension
# initializing dictionary
test_dict = {"Akash" : 1, "Akshat" : 2, "Nikhil" : 3, "Manjeet" : 4}
# initializing selective list keys
select_list = ['Manjeet', 'Nikhil']
# printing original dictionary
print ("The original dictionary is : " + str(test_dict))
# printing selective list
print ("The selective list is : " + str(select_list))
# using list comprehension
# getting selective dictionary keys
res = [test_dict[i] for i in select_list if i in test_dict]
# printing result
print ("The selected values from list keys is : " + str(res))
Output
The original dictionary is : {'Akash': 1, 'Akshat': 2, 'Nikhil': 3, 'Manjeet': 4}
The selective list is : ['Manjeet', 'Nikhil']
The selected values from list keys is : [4, 3]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using set.intersection() This is the most elegant method in which this task can be
performed. The intersection property of sets can give the common keys that can be extracted and
then values can be computed.
Python3
# Python3 code to demonstrate
# getting selective dictionary keys
# using set.intersection()
# initializing dictionary
test_dict = {"Akash" : 1, "Akshat" : 2, "Nikhil" : 3, "Manjeet" : 4}
# initializing selective list keys
select_list = ['Manjeet', 'Nikhil']
# printing original dictionary
print ("The original dictionary is : " + str(test_dict))
# printing selective list
print ("The selective list is : " + str(select_list))
# using set.intersection()
# getting selective dictionary keys
temp = list(set(select_list).intersection(test_dict))
res = [test_dict[i] for i in temp]
# printing result
print ("The selected values from list keys is : " + str(res))
Output
The original dictionary is : {'Akash': 1, 'Akshat': 2, 'Nikhil': 3, 'Manjeet': 4}
The selective list is : ['Manjeet', 'Nikhil']
The selected values from list keys is : [3, 4]
Time complexity: O(n), where n is the length of the longest input, i.e., the length of the list select_list
or the number of keys in the dictionary test_dict, whichever is larger. This is because the program
iterates through the list once to create a set, iterates through the dictionary once to check for
intersection, and iterates through the resulting keys once to retrieve the values.
Auxiliary space: O(m), where m is the number of keys in the resulting dictionary. This is because the
program creates a set and a list of length at most m to store the intersection of keys and the
corresponding values.
Method 3: Using simple for loop:
Initialize a dictionary called test_dict with some key-value pairs.
Initialize a list called select_list with some keys from the dictionary.
Print the original dictionary and the selective list.
Create an empty list called res to store the selected values from the dictionary.
Loop through each key in the select_list.
Check if the key exists in the test_dict dictionary using an if statement.
If the key exists, add the corresponding value to the res list using the append() method.
After all keys have been checked, print the res list, which contains the selected values from the
dictionary.
Python3
# initializing dictionary
test_dict = {"Akash": 1, "Akshat": 2, "Nikhil": 3, "Manjeet": 4}
# initializing selective list keys
select_list = ['Manjeet', 'Nikhil']
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# printing selective list
print("The selective list is : " + str(select_list))
# using for loop to iterate over selective list and get
# corresponding values from dictionary
res = []
for key in select_list:
# check if key is in dictionary
if key in test_dict:
# add corresponding value to result list
res.append(test_dict[key])
# printing result
print("The selected values from list keys is : " + str(res))
Output
The original dictionary is : {'Akash': 1, 'Akshat': 2, 'Nikhil': 3, 'Manjeet': 4}
The selective list is : ['Manjeet', 'Nikhil']
The selected values from list keys is : [4, 3]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 4: Using filter() function
The filter() function checks if each key in the selective list is present in the dictionary using the
__contains__() method of the dictionary. The resulting filtered list of keys is then passed to the
map() function along with the get() method of the dictionary. The map() function returns the values
corresponding to each key in the filtered list.
Python3
# initializing dictionary
test_dict = {"Akash" : 1, "Akshat" : 2, "Nikhil" : 3, "Manjeet" : 4}
# initializing selective list keys
select_list = ['Manjeet', 'Nikhil']
# using filter() and map() functions
# getting selective dictionary keys
res = list(map(test_dict.get, filter(test_dict.__contains__, select_list)))
# printing result
print ("The selected values from list keys is : " + str(res))
Output
The selected values from list keys is : [4, 3]
The time complexity of this approach is O(n), where n is the length of the selective list.
The auxiliary space complexity of this approach is O(m), where m is the number of keys in the
selective list that are also present in the dictionary.
Method#5: Using the Recursive method.
Step-by-step approach:
Initialize the dictionary and selective list.
Define a recursive function that takes the dictionary and the list of keys as parameters.
If the list of keys is empty, return an empty list.
Get the first key from the list.
Check if the key is in the dictionary.
If the key is in the dictionary, add its value to the result list.
Recursively call the function with the remaining keys in the list.
Concatenate the result of step 6 with the result of step 7.
Return the result list.
Below is the implementation of the above approach:
Python3
# defining the recursive function
def get_values_recursive(dictionary, keys):
# base case: if the list of keys is empty
if not keys:
return []
# get the first key from the list
key = keys[0]
# if the key is in the dictionary, add its value to the result list
if key in dictionary:
res = [dictionary[key]]
else:
res = []
# recursively call the function with the remaining keys in the list
res += get_values_recursive(dictionary, keys[1:])
return res
# initializing dictionary
test_dict = {"Akash": 1, "Akshat": 2, "Nikhil": 3, "Manjeet": 4}
# initializing selective list keys
select_list = ['Manjeet', 'Nikhil']
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# printing selective list
print("The selective list is : " + str(select_list))
# calling the recursive function to get the values for the selected keys
res = get_values_recursive(test_dict, select_list)
# printing result
print("The selected values from list keys is : " + str(res))
Python | Filter the negative values from given dictionary
garg_ak0109
Read
Discuss
Courses
Practice
Given a dictionary, the task is to filter all the negative values from given dictionary. Let’s discuss few
methods to do this task.
Method #1: Using dict comprehension
Follow the below steps to implement:
Initializing a dictionary named ini_dict with some key-value pairs.
Print the initial dictionary using the print() function.
Next, create a new dictionary named result using dictionary comprehension. Dictionary
comprehension is a concise way to create dictionaries from other iterables like lists, tuples, and sets.
In the dictionary comprehension, iterate over the key-value pairs of the ini_dict using
the items() method.
For each key-value pair, check if the value is greater than or equal to 0 using the if condition.
If the condition is true, add the key-value pair to the new dictionary result.
Finally, print the filtered dictionary result using the print() function.
Below is the implementation of the above approach:
Python3
# Python code to demonstrate
# return the filtered dictionary
# on certain criteria
# Initialising dictionary
ini_dict = {'a':1, 'b':-2, 'c':-3, 'd':7, 'e':0}
# printing initial dictionary
print ("initial lists", str(ini_dict))
# filter dictionary such that no value is greater than 0
result = dict((k, v) for k, v in ini_dict.items() if v >= 0)
print("resultant dictionary : ", str(result))
Output
initial lists {'a': 1, 'b': -2, 'c': -3, 'd': 7, 'e': 0}
resultant dictionary : {'a': 1, 'd': 7, 'e': 0}
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #2: Using lambda and filter
Python3
# Python code to demonstrate
# return the filtered dictionary
# on certain criteria
# Initialising dictionary
ini_dict = {'a':1, 'b':-2, 'c':-3, 'd':7, 'e':0}
# printing initial dictionary
print ("initial lists", str(ini_dict))
# filter dictionary such that no value is greater than 0
result = dict(filter(lambda x: x[1] >= 0.0, ini_dict.items()))
result = dict(result)
print("resultant dictionary : ", str(result))
Output
initial lists {'a': 1, 'b': -2, 'c': -3, 'd': 7, 'e': 0}
resultant dictionary : {'a': 1, 'd': 7, 'e': 0}
Time Complexity: O(n) where n is the number of elements in the dictionary.
Auxiliary Space: O(n) as the size of the resultant dictionary can be equal to the number of elements
in the initial dictionary.
Method #3 : Using find() method
Python3
# Python code to demonstrate
# return the filtered dictionary
# on certain criteria
# Initialising dictionary
ini_dict = {'a': 1, 'b': -2, 'c': -3, 'd': 7, 'e': 0}
# printing initial dictionary
print("initial lists", str(ini_dict))
# filter dictionary such that no value is greater than 0
res = dict()
for i in ini_dict:
if(str(ini_dict[i]).find("-") != 0):
res[i] = ini_dict[i]
print("resultant dictionary : ", str(res))
Output
initial lists {'a': 1, 'b': -2, 'c': -3, 'd': 7, 'e': 0}
resultant dictionary : {'a': 1, 'd': 7, 'e': 0}
The time complexity of this code is O(n), where n is the number of items in the initial dictionary
ini_dict.
The auxiliary space used by this code is O(n).
Method #4 : Using map() and a custom function
Here is an example of using map() and a custom function to filter negative values from a dictionary:
Python3
#If the value is negative, it returns None.
def filter_negative(item):
key, value = item
if value < 0:
return
return (key, value)
#Initialize the dictionary
ini_dict = {'a': 1, 'b': -2, 'c': -3, 'd': 7, 'e': 0}
#Use map to apply the filter_negative function to each item in the dictionary and return a map
object
#Use filter to remove the None values from the map object
#Use dict to convert the map object to a dictionary
result = dict(filter(None, map(filter_negative, ini_dict.items())))
#Print the resulting dictionary
print(result)
#This code is contributed by Edula Vinay Kumar Reddy
Output
{'a': 1, 'd': 7, 'e': 0}
The filter_negative() function takes a tuple representing a key-value pair in the dictionary, and
returns the tuple if the value is non-negative. If the value is negative, the function returns None,
which is filtered out by the filter() function. The map() function applies filter_negative() to each item
in the dictionary, producing a list of tuples. The filter() function then filters out any None values, and
the resulting list is passed to dict() to create the final filtered dictionary.
Time complexity: O(n), where n is the number of items in the dictionary. T
Auxiliary Space: O(n), as the filtered dictionary will have a size equal to the number of non-negative
values in the original dictionary.
Method #5 : Using startswith() method
Python3
# Python code to demonstrate
# return the filtered dictionary
# on certain criteria
# Initialising dictionary
ini_dict = {'a': 1, 'b': -2, 'c': -3, 'd': 7, 'e': 0}
# printing initial dictionary
print("initial lists", str(ini_dict))
# filter dictionary such that no value is greater than 0
res = dict()
for i in list(ini_dict.keys()):
x=str(ini_dict[i])
if(not x.startswith("-")):
res[i]=ini_dict[i]
print("resultant dictionary : ", str(res))
Output
initial lists {'a': 1, 'b': -2, 'c': -3, 'd': 7, 'e': 0}
resultant dictionary : {'a': 1, 'd': 7, 'e': 0}
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #6: Using list comprehension and dict() constructor
Step-by-step approach:
Initialize the dictionary ini_dict
Print the initial dictionary ini_dict
Use a list comprehension to filter the dictionary such that no value is greater than 0. Store the
resulting key-value pairs as a list of tuples.
Convert the list of tuples into a dictionary using the dict() constructor.
Print the resultant dictionary result.
Compute the time complexity and auxiliary space complexity.
Below is the implementation of the above approach:
Python3
# Python code to demonstrate
# return the filtered dictionary
# on certain criteria
# Initialising dictionary
ini_dict = {'a':1, 'b':-2, 'c':-3, 'd':7, 'e':0}
# printing initial dictionary
print ("initial dictionary:", ini_dict)
# using list comprehension and dict() constructor
result = dict([(k, v) for k, v in ini_dict.items() if v >= 0])
# printing resultant dictionary
print("resultant dictionary:", result)
# compute time complexity and auxiliary space
# time complexity: O(N)
# auxiliary space: O(N)
Spatial Filters – Averaging filter and Median filter in Image Processing
AmiMunshi
Read
Discuss
Courses
Practice
Spatial Filtering technique is used directly on pixels of an image. Mask is usually considered to be
added in size so that it has a specific center pixel. This mask is moved on the image such that the
center of the mask traverses all image pixels.
In this article, we are going to cover the following topics –
To write a program in Python to implement spatial domain averaging filter and to observe its
blurring effect on the image without using inbuilt functions
To write a program in Python to implement spatial domain median filter to remove salt and pepper
noise without using inbuilt functions
Theory
Neighborhood processing in spatial domain: Here, to modify one pixel, we consider values of the
immediate neighboring pixels also. For this purpose, 3X3, 5X5, or 7X7 neighborhood mask can be
considered. An example of a 3X3 mask is shown below.
f(x-1, y-1) f(x-1, y) f(x-1, y+1)
f(x, y-1) f(x, y) f(x, y+1)
f(x+1, y-1) f(x+1, y) f(x+1, y+1)
Low Pass filtering: It is also known as the smoothing filter. It removes the high-frequency content
from the image. It is also used to blur an image. A low pass averaging filter mask is as shown.
1/9 1/9 1/9
1/9 1/9 1/9
1/9 1/9 1/9
High Pass Filtering: It eliminates low-frequency regions while retaining or enhancing the high-
frequency components. A high pass filtering mask is as shown.
-1/9 -1/9 -1/9
-1/9 8/9 -1/9
-1/9 -1/9 -1/9
Median Filtering: It is also known as nonlinear filtering. It is used to eliminate salt and pepper noise.
Here the pixel value is replaced by the median value of the neighboring pixel.
Below is the implementation.
Input Image:
Averaging Filter:
Python3
# Low Pass SPatial Domain Filtering
# to observe the blurring effect
import cv2
import numpy as np
# Read the image
img = cv2.imread('sample.png', 0)
# Obtain number of rows and columns
# of the image
m, n = img.shape
# Develop Averaging filter(3, 3) mask
mask = np.ones([3, 3], dtype = int)
mask = mask / 9
# Convolve the 3X3 mask over the image
img_new = np.zeros([m, n])
for i in range(1, m-1):
for j in range(1, n-1):
temp = img[i-1, j-1]*mask[0, 0]+img[i-1, j]*mask[0, 1]+img[i-1, j + 1]*mask[0, 2]+img[i, j-
1]*mask[1, 0]+ img[i, j]*mask[1, 1]+img[i, j + 1]*mask[1, 2]+img[i + 1, j-1]*mask[2, 0]+img[i + 1,
j]*mask[2, 1]+img[i + 1, j + 1]*mask[2, 2]
img_new[i, j]= temp
img_new = img_new.astype(np.uint8)
cv2.imwrite('blurred.tif', img_new)
Output:
In the above example, it is observed that the filtered image is slightly blurred. If we increase the size
of the averaging mask, more blurring can be obtained.
Median Filtering:
Python3
# Median Spatial Domain Filtering
import cv2
import numpy as np
# Read the image
img_noisy1 = cv2.imread('sample.png', 0)
# Obtain the number of rows and columns
# of the image
m, n = img_noisy1.shape
# Traverse the image. For every 3X3 area,
# find the median of the pixels and
# replace the center pixel by the median
img_new1 = np.zeros([m, n])
for i in range(1, m-1):
for j in range(1, n-1):
temp = [img_noisy1[i-1, j-1],
img_noisy1[i-1, j],
img_noisy1[i-1, j + 1],
img_noisy1[i, j-1],
img_noisy1[i, j],
img_noisy1[i, j + 1],
img_noisy1[i + 1, j-1],
img_noisy1[i + 1, j],
img_noisy1[i + 1, j + 1]]
temp = sorted(temp)
img_new1[i, j]= temp[4]
img_new1 = img_new1.astype(np.uint8)
cv2.imwrite('new_median_filtered.png', img_new1)
Python – Split Dictionary values on size limit of values
manjeet_04
Read
Discuss
Courses
Practice
Given a dictionary with string values, the task is to write a python program to split values if the size
of string exceeds K.
Input : {1 : “Geeksforgeeks”, 2 : “best for”, 3 : “all geeks”}, limit = 5
Output : {1: ‘Geeks’, 2: ‘forge’, 3: ‘eks’, 4: ‘best ‘, 5: ‘for’, 6: ‘all g’, 7: ‘eeks’}
Explanation : All string values are capped till length 5. New value is created post size limit.
Input : {1 : “Geeksforgeeks”, 2 : “best for”}, limit = 5
Output : {1: ‘Geeks’, 2: ‘forge’, 3: ‘eks’, 4: ‘best ‘, 5: ‘for’}
Explanation : All string values are capped till length 5. New value is created post size limit.
Method 1: Using dictionary comprehension + enumerate() + list slicing
In this, we perform the task of getting required value chunks using list slicing and list comprehension
on the iteration of values extracted using values(). The next step is to reassign keys with new
chunked values using list comprehension and enumerate().
Python3
# Python3 code to demonstrate working of
# Split Dictionary values on size limit
# Using dictionary comprehension + enumerate() + list slicing
# initializing dictionary
test_dict = {1: "Geeksforgeeks",
2: "best for", 3:
"all geeks"}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing limit
limit = 4
# cutting chunks of K
chunks = (sub[idx: idx + limit] for sub in test_dict.values()
for idx in range(0, len(sub), limit))
# re assigning dictionary with chunks
res = {key: val for key, val in enumerate(chunks, 1)}
# printing result
print("The extracted values : " + str(res))
Output:
The original dictionary is : {1: ‘Geeksforgeeks’, 2: ‘best for’, 3: ‘all geeks’}
The extracted values : {1: ‘Geek’, 2: ‘sfor’, 3: ‘geek’, 4: ‘s’, 5: ‘best’, 6: ‘ for’, 7: ‘all ‘, 8: ‘geek’, 9: ‘s’}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2: Using a for loop and string slicing
Step-by-step approach:
Initialize an empty dictionary called res.
Loop through each key-value pair in the test_dict.
For each value in the key-value pair, slice it into chunks of size limit using string slicing and store
them in a temporary list called chunks.
Loop through each chunk in chunks, and add it as a value to the res dictionary with a new key that is
incremented by 1 for each chunk.
Print the resulting dictionary res.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Split Dictionary values on size limit
# Using for loop and string slicing
# initializing dictionary
test_dict = {1: "Geeksforgeeks",
2: "best for", 3:
"all geeks"}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing limit
limit = 4
# initializing empty dictionary for result
res = {}
# loop through each key-value pair in test_dict
for key, value in test_dict.items():
# split value into chunks of size limit using string slicing
chunks = [value[i:i+limit] for i in range(0, len(value), limit)]
# loop through each chunk and add it to res with a new key
for i, chunk in enumerate(chunks):
res[len(res)+1] = chunk
# printing result
print("The extracted values : " + str(res))
Output
The original dictionary is : {1: 'Geeksforgeeks', 2: 'best for', 3: 'all geeks'}
The extracted values : {1: 'Geek', 2: 'sfor', 3: 'geek', 4: 's', 5: 'best', 6: ' for', 7: 'all ', 8: 'geek', 9: 's'}
Time complexity: O(nm), where n is the number of key-value pairs in test_dict and m is the
maximum length of any value in test_dict.
Auxiliary space: O(nm), since we are creating a new dictionary with the same number of key-value
pairs as test_dict, and each value can be split into multiple chunks of size limit.
Method 3: Using a while loop and dictionary update
Step-by-step approach:
Initialize the original dictionary test_dict.
Print the original dictionary.
Initialize the size limit.
Create an empty dictionary res to store the result.
Loop over the items in the original dictionary using items().
Initialize the start index start to 0.
While the start index is less than the length of the value, do the following:
a. Calculate the end index end for slicing by adding the limit to the start index.
b. Slice the value using the start and end indices, and add the result to the result dictionary with a
new key.
c. Increment the start index by the limit.
Print the result dictionary.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Split Dictionary values on size limit
# Using while loop and dictionary update
# initializing dictionary
test_dict = {1: "Geeksforgeeks",
2: "best for", 3:
"all geeks"}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing limit
limit = 4
# create an empty dictionary to store the result
res = {}
# loop over the items in the original dictionary
for key, value in test_dict.items():
# initialize the start index for slicing
start = 0
# split the value into chunks of size limit
while start < len(value):
# get the end index for slicing
end = start + limit
# slice the value and add it to the result dictionary
res[len(res) + 1] = value[start:end]
# increment the start index
start = end
# printing result
print("The extracted values : " + str(res))
Output
The original dictionary is : {1: 'Geeksforgeeks', 2: 'best for', 3: 'all geeks'}
The extracted values : {1: 'Geek', 2: 'sfor', 3: 'geek', 4: 's', 5: 'best', 6: ' for', 7: 'all ', 8: 'geek', 9: 's'}
Time complexity: O(n*m), where n is the number of values in the original dictionary and m is the
maximum length of a value in the dictionary.
Auxiliary space: O(n*m), because we need to create a new dictionary to store the result, and the size
of this dictionary is proportional to the number of values in the original dictionary and the maximum
length of a value.
Method 4: Using list comprehension and dictionary update
Step-by-step approach:
Start by initializing the original dictionary and the size limit.
Create an empty dictionary to store the result.
Use list comprehension to split each value in the dictionary into chunks of size limit.
Loop over the items in the original dictionary, and use dictionary update to add each chunk as a new
value to the result dictionary.
Print the result.
Below is the implementation of the above approach:
Python3
# initializing dictionary
test_dict = {1: "Geeksforgeeks",
2: "best for", 3:
"all geeks"}
# initializing limit
limit = 4
# create an empty dictionary to store the result
res = {}
# use list comprehension to split each value in the dictionary into chunks of size limit
chunks = [value[i:i+limit] for value in test_dict.values() for i in range(0, len(value), limit)]
# loop over the items in the original dictionary and use dictionary update to add each chunk as a
new value to the result dictionary
for i, chunk in enumerate(chunks):
res[i+1] = chunk
# printing result
print("The extracted values : " + str(res))
Output
The extracted values : {1: 'Geek', 2: 'sfor', 3: 'geek', 4: 's', 5: 'best', 6: ' for', 7: 'all ', 8: 'geek', 9: 's'}
Time complexity: O(nm), where n is the number of items in the dictionary and m is the length of the
longest value in the dictionary.
Auxiliary space: O(nm), to store the chunks of each value in the list comprehension.
Method 5: Using built-in function divmod()
Step-by-step approach:
Initialize the original dictionary, test_dict.
Set the limit of each chunk, limit.
Initialize an empty dictionary to store the split chunks, res.
Loop through each key-value pair in test_dict.
Calculate the number of chunks needed to split the value, num_chunks, using divmod().
Split the value into num_chunks chunks using a list comprehension and string slicing, and store them
in a list, chunks.
Loop through each chunk in chunks, and add it to res with a new key.
Return the res dictionary.
Python3
# Python3 code to demonstrate working of
# Split Dictionary values on size limit
# Using divmod() and list comprehension
# initializing dictionary
test_dict = {1: "Geeksforgeeks",
2: "best for",
3: "all geeks"}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing limit
limit = 4
# initializing empty dictionary for result
res = {}
# loop through each key-value pair in test_dict
for key, value in test_dict.items():
# calculate the number of chunks needed to split the value
num_chunks, remainder = divmod(len(value), limit)
if remainder:
num_chunks += 1
# split value into chunks of size limit using string slicing
chunks = [value[i:i+limit] for i in range(0, len(value), limit)]
# loop through each chunk and add it to res with a new key
for i, chunk in enumerate(chunks):
res[len(res)+1] = chunk
# printing result
print("The extracted values : " + str(res))
Output
Python – Extract Unique values dictionary values
manjeet_04
Read
Discuss
Courses
Practice
Sometimes, while working with data, we can have problem in which we need to perform the
extraction of only unique values from dictionary values list. This can have application in many
domains such as web development. Lets discuss certain ways in which this task can be performed.
Method #1 : Using sorted() + set comprehension + values() The combination of above functionalities
can be used to perform this task. In this, we extract all the values using values() and set
comprehension is used to get unique values compiled in list.
Python3
# Python3 code to demonstrate working of
# Extract Unique values dictionary values
# Using set comprehension + values() + sorted()
# initializing dictionary
test_dict = {'gfg': [5, 6, 7, 8],
'is': [10, 11, 7, 5],
'best': [6, 12, 10, 8],
'for': [1, 2, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Extract Unique values dictionary values
# Using set comprehension + values() + sorted()
res = list(sorted({ele for val in test_dict.values() for ele in val}))
# printing result
print("The unique values list is : " + str(res))
Output
The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2, 5]}
The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
Method #2 : Using chain() + sorted() + values() This performs the task in similar way. The difference
is that the task of set comprehension is performed using chain().
Python3
# Python3 code to demonstrate working of
# Extract Unique values dictionary values
# Using chain() + sorted() + values()
from itertools import chain
# initializing dictionary
test_dict = {'gfg': [5, 6, 7, 8],
'is': [10, 11, 7, 5],
'best': [6, 12, 10, 8],
'for': [1, 2, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Extract Unique values dictionary values
# Using chain() + sorted() + values()
res = list(sorted(set(chain(*test_dict.values()))))
# printing result
print("The unique values list is : " + str(res))
Output
The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2, 5]}
The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]
The time complexity of the code is O(nlog(n)) where n is the total number of elements in all the lists
of the dictionary.
The auxiliary space complexity of the code is O(n) because it creates a new list of all the values in the
dictionary using the values() method, which requires O(n) space.
Method #3: Using keys(),extend(),list(),set() and sort() methods
Python3
# Python3 code to demonstrate working of
# Extract Unique values dictionary values
# initializing dictionary
test_dict = {'gfg' : [5, 6, 7, 8],
'is' : [10, 11, 7, 5],
'best' : [6, 12, 10, 8],
'for' : [1, 2, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Extract Unique values dictionary values
x=[]
for i in test_dict.keys():
x.extend(test_dict[i])
x=list(set(x))
x.sort()
# printing result
print("The unique values list is : " + str(x))
Output
The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2, 5]}
The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]
Time complexity: O(n*m*log(m)), where n is the number of keys in the dictionary and m is the
maximum length of the lists in the dictionary.
Auxiliary space: O(n*m), where n is the number of keys in the dictionary and m is the maximum
length of the lists in the dictionary.
Method #4 : Using extend() and sort() methods
Python3
# Python3 code to demonstrate working of
# Extract Unique values dictionary values
# initializing dictionary
test_dict = {'gfg' : [5, 6, 7, 8],
'is' : [10, 11, 7, 5],
'best' : [6, 12, 10, 8],
'for' : [1, 2, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
x=list(test_dict.values())
y=[]
res=[]
for i in x:
y.extend(i)
for i in y:
if i not in res:
res.append(i)
res.sort()
# printing result
print("The unique values list is : " + str(res))
Output
The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2, 5]}
The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
Method #5: Using Counter(),append() and sort() methods
Import the Counter class from the collections module.
Define a dictionary test_dict with string keys and lists of integers as values.
Print the original dictionary.
Create an empty list called valuesList.
Iterate over the dictionary using the items() method to access the keys and values. For each key-
value pair, iterate over the values list and append each value to valuesList.
Use the Counter() function to count the frequency of each value in valuesList. This creates a
dictionary where the keys are the unique values in valuesList and the values are their frequencies.
Use the keys() method to extract a list of the unique values from freq.
Sort the uniqueValues list in ascending order.
Print the final list of unique values
Python3
# Python3 code to demonstrate working of
# Extract Unique values dictionary values
# initializing dictionary
from collections import Counter
test_dict = {'gfg': [5, 6, 7, 8],
'is': [10, 11, 7, 5],
'best': [6, 12, 10, 8],
'for': [1, 2, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
valuesList = []
for key, values in test_dict.items():
for value in values:
valuesList.append(value)
freq = Counter(valuesList)
uniqueValues = list(freq.keys())
uniqueValues.sort()
# printing result
print("The unique values list is : " + str(uniqueValues))
Output
The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2, 5]}
The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]
The time complexity of the above program is O(nmlog(m)), where n is the number of keys in the
dictionary and m is the average number of values per key.
Auxiliary space complexity is O(n*m).
Method #6:Using Operator.countOf() method
STEPS:
Import the “operator” module as “op”.
Create a dictionary called “test_dict” and initialize it with some key-value pairs where each key is a
string and the value is a list of integers.
Print the original dictionary using the “print()” function.
Create an empty list called “x”.
Get all the values of the dictionary and append them to the list “x” using the “list()” function and the
“values()” method of the dictionary.
Create an empty list called “y”.
Iterate over each item in the list “x” using a for loop and append all the elements of each list to the
list “y” using the “extend()” method.
Create an empty list called “res”.
Iterate over each item in the list “y” using a for loop.
Check if the count of the current item in the list “res” is zero using the “countOf()” method of the
“operator” module.
If the count is zero, append the current item to the list “res” using the “append()” method.
Sort the list “res” using the “sort()” method.
Print the unique values list using the “print()” function.
Python3
# Python3 code to demonstrate working of
# Extract Unique values dictionary values
import operator as op
# initializing dictionary
test_dict = {'gfg' : [5, 6, 7, 8],
'is' : [10, 11, 7, 5],
'best' : [6, 12, 10, 8],
'for' : [1, 2, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
x=list(test_dict.values())
y=[]
res=[]
for i in x:
y.extend(i)
for i in y:
if op.countOf(res,i)==0:
res.append(i)
res.sort()
# printing result
print("The unique values list is : " + str(res))
Output
The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2, 5]}
The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]
Auxiliary Space: O(N*N)
Time Complexity:O(N)
Method 7: Using set() + sum()
Python3
#Python3 code to demonstrate working of
#Extract Unique values dictionary values
#initializing dictionary
test_dict = {'gfg' : [5, 6, 7, 8],
'is' : [10, 11, 7, 5],
'best' : [6, 12, 10, 8],
'for' : [1, 2, 5]}
#printing original dictionary
print("The original dictionary is : " + str(test_dict))
#Extract Unique values dictionary values
result = list(set(sum(test_dict.values(), [])))
#printing result
print("The unique values list is : " + str(result))
Python – Filter dictionary values in heterogeneous dictionary
manjeet_04
Read
Discuss
Courses
Practice
Sometimes, while working with Python dictionaries, we can have a problem in which we need to
filter out certain values based on certain conditions on a particular type, e.g all values smaller than K.
This task becomes complex when dictionary values can be heterogeneous. This kind of problem can
have applications across many domains. Let’s discuss certain ways in which this task can be
performed.
Input : test_dict = {‘Gfg’ : 10, ‘for’ : ‘geeks’}
Output : {‘Gfg’: 10, ‘for’: ‘geeks’}
Input : test_dict = {‘Gfg’ : ‘geeks’}
Output : {‘Gfg’: ‘geeks’}
Method #1 : Using type() + dictionary comprehension
The combination of above functions can be used to perform this task. In this, we check for integral
type using type() and filter the data in dictionary comprehension.
Step-by-step approach
Use dictionary comprehension to create a new dictionary res.
Iterate over the items of test_dict using the items() method.
For each item, check if the value is not an integer (type(val) != int) or if it is greater than K (val > K).
If the condition is true, add the key-value pair to the new dictionary res.
Print the new dictionary res using the print() function.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using type() + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K=3
# Filter dictionary values in heterogeneous dictionary
# Using type() + dictionary comprehension
res = {key : val for key, val in test_dict.items()
if type(val) != int or val > K}
# printing result
print("Values greater than K : " + str(res))
Output :
The original dictionary : {'Gfg': 4, 'for': 'geeks', 'is': 2, 'best': 3}
Values greater than K : {'Gfg': 4, 'for': 'geeks'}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using isinstance() + dictionary comprehension
The combination of above functions can also be used to solve this problem. In this, we perform this
task similar to above, but the difference being that type test is done by isinstance() rather than
type().
Python3
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using isinstance() + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K=3
# Filter dictionary values in heterogeneous dictionary
# Using isinstance() + dictionary comprehension
res = {key : val for key, val in test_dict.items()
if not isinstance(val, int) or val > K}
# printing result
print("Values greater than K : " + str(res))
Output :
The original dictionary : {'Gfg': 4, 'for': 'geeks', 'is': 2, 'best': 3}
Values greater than K : {'Gfg': 4, 'for': 'geeks'}
Time complexity: O(n), where n is the number of items in the dictionary.
Auxiliary space: O(k), where k is the number of items in the resulting dictionary after filtering.
Method 3: Using a for loop and conditional statements:
Step-by-step approach:
Initialize a dictionary test_dict with some key-value pairs.
Print the original dictionary using print(“The original dictionary : ” + str(test_dict)).
Initialize an integer K with value 3.
Create an empty dictionary res to store the filtered values.
Loop through the key-value pairs of the dictionary using for key, val in test_dict.items()
Use a conditional statement to filter the dictionary values. If the value is not an integer or it is
greater than K, we add it to the res dictionary using res[key] = val.
Print the filtered dictionary using print(“Values greater than K : ” + str(res)).
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using for loop and conditional statements
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K=3
# Filter dictionary values in heterogeneous dictionary
# Using for loop and conditional statements
res = {}
for key, val in test_dict.items():
if type(val) != int or val > K:
res[key] = val
# printing result
print("Values greater than K : " + str(res))
Output
The original dictionary : {'Gfg': 4, 'is': 2, 'best': 3, 'for': 'geeks'}
Values greater than K : {'Gfg': 4, 'for': 'geeks'}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary.
Method #4: Using a dictionary comprehension with if condition:
Step-by-step approach:
Initialize a dictionary test_dict with some key-value pairs.
Initialize a variable K with a value to compare against dictionary values.
Use dictionary comprehension to filter out the items from the dictionary.
Loop through each key-value pair in the dictionary and check if the value is either non-integer or
greater than K.
If the value satisfies the condition, add the key-value pair to the result dictionary.
Return the filtered dictionary.
Below is the implementation of the above approach:
Python3
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# initializing K
K=3
# Filter dictionary values in heterogeneous dictionary
# Using dictionary comprehension with if condition
res = {k:v for k, v in test_dict.items() if type(v) != int or v > K}
# printing result
print("Values greater than K : " + str(res))
Output
Values greater than K : {'Gfg': 4, 'for': 'geeks'}
Time complexity: O(n) as it loops through all the items in the dictionary once.
Auxiliary space: O(n) as it creates a new dictionary to store the filtered items.
Method #6: Using filter() function with lambda function
Step-by-step approach:
Initialize a variable K with a value of 3.
Use the filter() function to filter the items in the test_dict dictionary using a lambda function. The
lambda function checks if an item’s value is not an integer or is greater than K.
Convert the filtered items into a dictionary using the dict() function.
Assign the filtered dictionary to a variable named res.
Print the filtered dictionary using the print() function.
Below is the implementation of the above approach:
Python3
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K=3
# Filter dictionary values in heterogeneous dictionary
# Using filter() function with lambda function
res = dict(filter(lambda item: not(isinstance(item[1], int) and item[1] <= K), test_dict.items()))
# printing result
print("Values greater than K : " + str(res))
Python – Replace dictionary value from other dictionary
manjeet_04
Read
Discuss
Courses
Practice
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.
Input : test_dict = {“Gfg” : 5, “is” : 8, “Best” : 10, “for” : 8, “Geeks” : 9}, updict = {“Geek” : 10, “Bet” :
17}
Output : {‘Gfg’: 5, ‘is’: 8, ‘Best’: 10, ‘for’: 8, ‘Geeks’: 9}
Explanation : No values matched, hence original dictionary.
Method #1 : Using loop
This is brute way in which this task can be performed. In this, we run a loop for each key in target
dictionary and update in case the value is present in other dictionary.
Python3
# Python3 code to demonstrate working of
# Replace dictionary value from other dictionary
# Using loop
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing updict
updict = {"Gfg" : 10, "Best" : 17}
for sub in test_dict:
# checking if key present in other dictionary
if sub in updict:
test_dict[sub] = updict[sub]
# printing result
print("The updated dictionary: " + str(test_dict))
Output
The original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 9}
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using dictionary comprehension
This is one liner approach in which this task can be performed. In this, we iterate for all the
dictionary values and update in a one-liner manner in dictionary comprehension.
Python3
# Python3 code to demonstrate working of
# Replace dictionary value from other dictionary
# Using dictionary comprehension
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing updict
updict = {"Gfg" : 10, "Best" : 17}
res = {key: updict.get(key, test_dict[key]) for key in test_dict}
# printing result
print("The updated dictionary: " + str(res))
Output
The original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 9}
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
Time complexity: O(n),
Auxiliary space: O(m),
Method #3: Using dict.update() method
This program updates the values of certain keys in a dictionary by using the update() method. It
initializes two dictionaries (test_dict and updict), updates the values of the keys “Gfg” and “Best” in
test_dict using the corresponding values in updict, and then prints the updated test_dict.
Python3
# Python3 code to demonstrate working of
# Replace dictionary value from other dictionary
# Using dict.update() method
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing updict
updict = {"Gfg" : 10, "Best" : 17}
# updating dictionary using dict.update() method
test_dict.update(updict)
# printing result
print("The updated dictionary: " + str(test_dict))
Output
The original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 9}
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
Time complexity: O(m), where m is the size of the updict.
Auxiliary space: O(1), as the algorithm updates the existing dictionary in place and does not use any
additional space proportional to the size of the input.
Method #5: Using the built-in map() function and a lambda function
In this method, we first create a list of updated values by mapping a lambda function to the keys of
the original dictionary. The lambda function checks if the key is present in the second dictionary, and
if it is, returns the corresponding value from the second dictionary. Otherwise, it returns the value
from the original dictionary.
Python3
test_dict = {"Gfg": 5, "is": 8, "Best": 10, "for": 8, "Geeks": 9}
updict = {"Gfg": 10, "Best": 17}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
updated_values = map(
lambda key: updict[key] if key in updict else test_dict[key], test_dict)
updated_dict = dict(zip(test_dict.keys(), updated_values))
test_dict = {"Gfg": 5, "is": 8, "Best": 10, "for": 8, "Geeks": 9}
updict = {"Gfg": 10, "Best": 17}
updated_values = map(
lambda key: updict[key] if key in updict else test_dict[key], test_dict)
updated_dict = dict(zip(test_dict.keys(), updated_values))
print("The updated dictionary: " + str(updated_dict))
Output
The original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 9}
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
The time complexity of this code is O(N), where N is the number of key-value pairs in the test_dict.
The auxiliary space complexity of this code is also O(N), as we use a map() object to store the
updated values, and then we create a new dictionary using the zip() function.
Method 6: Using defaultdict
Use the defaultdict class from the collections module to create a new dictionary with default values
set to the values of the original dictionary. We will then update the values of the keys present in the
updict.
Step-by-step approach:
Create a defaultdict with default values from the original dictionary
Update the values of the keys present in the updict
Convert the defaultdict back to a regular dictionary
Below is the implementation of the above approach:
Python3
from collections import defaultdict
test_dict = {"Gfg": 5, "is": 8, "Best": 10, "for": 8, "Geeks": 9}
updict = {"Gfg": 10, "Best": 17}
# create a defaultdict with default values from the original dictionary
default_dict = defaultdict(lambda: None, test_dict)
# update the values of the keys present in the updict
for key, value in updict.items():
default_dict[key] = value
# convert the defaultdict back to a regular dictionary
updated_dict = dict(default_dict)
print("The updated dictionary: " + str(updated_dict))
Python – Append Dictionary Keys and Values ( In order ) in dictionary
manjeet_04
Read
Discuss
Courses
Practice
Given a dictionary, perform append of keys followed by values in list.
Input : test_dict = {“Gfg” : 1, “is” : 2, “Best” : 3}
Output : [‘Gfg’, ‘is’, ‘Best’, 1, 2, 3]
Explanation : All the keys before all the values in list.
Input : test_dict = {“Gfg” : 1, “Best” : 3}
Output : [‘Gfg’, ‘Best’, 1, 3]
Explanation : All the keys before all the values in list.
Method #1 : Using list() + keys() + values()
This is one of the ways in which this task can be performed. In this, we extract keys and values using
keys() and values(), convert then to list using list() and perform append in order.
Python3
# Python3 code to demonstrate working of
# Append Dictionary Keys and Values ( In order ) in dictionary
# Using values() + keys() + list()
# initializing dictionary
test_dict = {"Gfg" : 1, "is" : 3, "Best" : 2}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# + operator is used to perform adding keys and values
res = list(test_dict.keys()) + list(test_dict.values())
# printing result
print("The ordered keys and values : " + str(res))
Output
The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
The ordered keys and values : ['Gfg', 'is', 'Best', 1, 3, 2]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using chain() + keys() + values()
This is one of the ways in which this task can be performed. In this, we bind keys with values
together in order using chain().
Python3
# Python3 code to demonstrate working of
# Append Dictionary Keys and Values ( In order ) in dictionary
# Using chain() + keys() + values()
from itertools import chain
# initializing dictionary
test_dict = {"Gfg" : 1, "is" : 3, "Best" : 2}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# chain() is used for concatenation
res = list(chain(test_dict.keys(), test_dict.values()))
# printing result
print("The ordered keys and values : " + str(res))
Output
The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
The ordered keys and values : ['Gfg', 'is', 'Best', 1, 3, 2]
Time complexity: O(n), where n is the size of the dictionary.
Auxiliary space: O(n), as we are creating a list of size 2n to store the concatenated keys and values.
Method #3 : Using list() +keys() + values() + extend()
Python3
# Python3 code to demonstrate working of
# Append Dictionary Keys and Values
#( In order ) in dictionary
# Using values() + keys() + extend()+list()
# initializing dictionary
test_dict = {"Gfg": 1, "is": 3, "Best": 2}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
a = list(test_dict.keys())
b = list(test_dict.values())
a.extend(b)
res = a
# printing result
print("The ordered keys and values : " + str(res))
Output
The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
The ordered keys and values : ['Gfg', 'is', 'Best', 1, 3, 2]
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary.
Method #4: Using zip() function and list comprehension
This program initializes a dictionary and prints it. It then uses a zip() function and list comprehension
to create a list of key-value pairs where the values come first, and then the keys. It finally prints the
ordered key-value pairs.
Python3
# initializing dictionary
test_dict = {"Gfg": 1, "is": 3, "Best": 2}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using the zip() function and list comprehension to append dictionary keys and values
res = [val for val in zip(test_dict.values(), test_dict.keys())]
# printing result
print("The ordered keys and values : " + str(res))
Output
The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
The ordered keys and values : [(1, 'Gfg'), (3, 'is'), (2, 'Best')]
Time complexity: O(n), where n is the number of items in the dictionary.
Auxiliary space: O(n), as we are creating a list of n items using the list comprehension.
Method #5: Using sorted() function and list comprehension
Step-by-step approach:
Initialize the dictionary test_dict.
Print the original dictionary using the print() function.
Use the sorted() function to get the keys in alphabetical order, and assign the result to the keys
variable.
Use a list comprehension to get the values corresponding to each key in the keys list, and assign the
result to the values variable.
Concatenate the keys and values lists using the + operator, and assign the result to the res variable.
Print the ordered keys and values using the print() function.
Python3
# Python3 code to demonstrate working of
# Append Dictionary Keys and Values ( In order ) in dictionary
# Using sorted() + list comprehension
# initializing dictionary
test_dict = {"Gfg" : 1, "is" : 3, "Best" : 2}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using sorted() to get the keys in alphabetical order
keys = sorted(test_dict.keys())
# using list comprehension to get the values corresponding to each key
values = [test_dict[key] for key in keys]
# concatenating the keys and values lists
res = keys + values
# printing result
print("The ordered keys and values : " + str(res))
Python – Replace dictionary value from other dictionary
manjeet_04
Read
Discuss
Courses
Practice
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.
Input : test_dict = {“Gfg” : 5, “is” : 8, “Best” : 10, “for” : 8, “Geeks” : 9}, updict = {“Geek” : 10, “Bet” :
17}
Output : {‘Gfg’: 5, ‘is’: 8, ‘Best’: 10, ‘for’: 8, ‘Geeks’: 9}
Explanation : No values matched, hence original dictionary.
Method #1 : Using loop
This is brute way in which this task can be performed. In this, we run a loop for each key in target
dictionary and update in case the value is present in other dictionary.
Python3
# Python3 code to demonstrate working of
# Replace dictionary value from other dictionary
# Using loop
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing updict
updict = {"Gfg" : 10, "Best" : 17}
for sub in test_dict:
# checking if key present in other dictionary
if sub in updict:
test_dict[sub] = updict[sub]
# printing result
print("The updated dictionary: " + str(test_dict))
Output
The original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 9}
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using dictionary comprehension
This is one liner approach in which this task can be performed. In this, we iterate for all the
dictionary values and update in a one-liner manner in dictionary comprehension.
Python3
# Python3 code to demonstrate working of
# Replace dictionary value from other dictionary
# Using dictionary comprehension
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing updict
updict = {"Gfg" : 10, "Best" : 17}
res = {key: updict.get(key, test_dict[key]) for key in test_dict}
# printing result
print("The updated dictionary: " + str(res))
Output
The original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 9}
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
Time complexity: O(n),
Auxiliary space: O(m),
Method #3: Using dict.update() method
This program updates the values of certain keys in a dictionary by using the update() method. It
initializes two dictionaries (test_dict and updict), updates the values of the keys “Gfg” and “Best” in
test_dict using the corresponding values in updict, and then prints the updated test_dict.
Python3
# Python3 code to demonstrate working of
# Replace dictionary value from other dictionary
# Using dict.update() method
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing updict
updict = {"Gfg" : 10, "Best" : 17}
# updating dictionary using dict.update() method
test_dict.update(updict)
# printing result
print("The updated dictionary: " + str(test_dict))
Output
The original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 9}
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
Time complexity: O(m), where m is the size of the updict.
Auxiliary space: O(1), as the algorithm updates the existing dictionary in place and does not use any
additional space proportional to the size of the input.
Method #5: Using the built-in map() function and a lambda function
In this method, we first create a list of updated values by mapping a lambda function to the keys of
the original dictionary. The lambda function checks if the key is present in the second dictionary, and
if it is, returns the corresponding value from the second dictionary. Otherwise, it returns the value
from the original dictionary.
Python3
test_dict = {"Gfg": 5, "is": 8, "Best": 10, "for": 8, "Geeks": 9}
updict = {"Gfg": 10, "Best": 17}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
updated_values = map(
lambda key: updict[key] if key in updict else test_dict[key], test_dict)
updated_dict = dict(zip(test_dict.keys(), updated_values))
test_dict = {"Gfg": 5, "is": 8, "Best": 10, "for": 8, "Geeks": 9}
updict = {"Gfg": 10, "Best": 17}
updated_values = map(
lambda key: updict[key] if key in updict else test_dict[key], test_dict)
updated_dict = dict(zip(test_dict.keys(), updated_values))
print("The updated dictionary: " + str(updated_dict))
Output
The original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 9}
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
The time complexity of this code is O(N), where N is the number of key-value pairs in the test_dict.
The auxiliary space complexity of this code is also O(N), as we use a map() object to store the
updated values, and then we create a new dictionary using the zip() function.
Method 6: Using defaultdict
Use the defaultdict class from the collections module to create a new dictionary with default values
set to the values of the original dictionary. We will then update the values of the keys present in the
updict.
Step-by-step approach:
Create a defaultdict with default values from the original dictionary
Update the values of the keys present in the updict
Convert the defaultdict back to a regular dictionary
Below is the implementation of the above approach:
Python3
from collections import defaultdict
test_dict = {"Gfg": 5, "is": 8, "Best": 10, "for": 8, "Geeks": 9}
updict = {"Gfg": 10, "Best": 17}
# create a defaultdict with default values from the original dictionary
default_dict = defaultdict(lambda: None, test_dict)
# update the values of the keys present in the updict
for key, value in updict.items():
default_dict[key] = value
# convert the defaultdict back to a regular dictionary
updated_dict = dict(default_dict)
print("The updated dictionary: " + str(updated_dict))
Output
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
Time complexity: O(N+M), where N is the number of keys in the original dictionary and M is the
number of keys in the updict.
Auxiliary space: O(N), where N is the number of keys in the original dictionary.
Python – Replace value by Kth index value in Dictionary List
manjeet_04
Read
Discuss
Courses
Practice
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’: 9, ‘is’: 8, ‘good’: 10}, {‘gfg’: 1, ‘for’: 10, ‘geeks’: 9}, {‘love’: 3, ‘gfg’: 9}]
Explanation : gfg is assigned with 9 which is 2nd index in list.
Input : test_list = [{‘gfg’ : [5, 7, 9, 1], ‘is’ : 8, ‘good’ : 10}, {‘gfg’ : 1, ‘for’ : 10, ‘geeks’ : 9}], K = 2, key =
“gfg”
Output : [{‘gfg’: 9, ‘is’: 8, ‘good’: 10}, {‘gfg’: 1, ‘for’: 10, ‘geeks’: 9}]
Explanation : gfg is assigned with 9 which is 2nd index in list.
Method #1 : Using loop + isinstance()
Use isinstance() to check for list type of values and loop is used to iterate through dictionaries.
Step-by-step approach :
Loop over each dictionary sub in the list test_list.
Use the isinstance() function to check if the value corresponding to the key key is a list in the current
dictionary sub.
If the value is a list, update the value corresponding to the key key with the Kth element of the list.
Print the modified list of dictionaries test_list.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Replace value by Kth index value in Dictionary List
# Using loop + isinstance()
# initializing list
test_list = [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': [7, 3, 9, 1]}]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K=2
# initializing Key
key = "gfg"
for sub in test_list:
# using isinstance() to check for list
if isinstance(sub[key], list):
sub[key] = sub[key][K]
# printing result
print("The Modified Dictionaries : " + str(test_list))
Output
The original list is : [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg':
[7, 3, 9, 1]}]
The Modified Dictionaries : [{'gfg': 9, 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg':
9}]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using dictionary comprehension + isinstance()
In this, we reconstruct dictionaries with modified dictionary values using isinstance() and dictionary
comprehension is used to form intermediate dictionaries.
Python3
# Python3 code to demonstrate working of
# Replace value by Kth index value in Dictionary List
# Using dictionary comprehension + isinstance()
# initializing list
test_list = [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': [7, 3, 9, 1]}]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K=2
# initializing Key
key = "gfg"
# intermediate Dictionaries constructed using dictionary comprehension
res = [{newkey: (val[K] if isinstance(val, list) and newkey == key else val)
for newkey, val in sub.items()} for sub in test_list]
# printing result
print("The Modified Dictionaries : " + str(res))
Output
The original list is : [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg':
[7, 3, 9, 1]}]
The Modified Dictionaries : [{'gfg': 9, 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg':
9}]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 3: Modifying the original list in-place using a list comprehension:
This approach uses a list comprehension to create a new list of dictionaries with the specified key
updated at index K, and then assigns the new list back to the original variable to modify it in-place.
The output of this code should match exactly with the original program.
Python3
# initializing list
test_list = [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': [7, 3, 9, 1]}]
# printing original list
print("The original list is : " + str(test_list))
# initializing K and key
K=2
key = "gfg"
# modifying the original list in-place using a list comprehension
test_list = [{k: (v[K] if k == key and isinstance(v, list) else v) for k, v in d.items()} for d in test_list]
# printing result
print("The Modified Dictionaries : " + str(test_list))
Output
The original list is : [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg':
[7, 3, 9, 1]}]
The Modified Dictionaries : [{'gfg': 9, 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg':
9}]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using for loop and try-except block
we can use a for loop to iterate over the dictionaries in the list, and a try-except block to check if the
key is present and if the value is a list. If the conditions are satisfied, we can replace the value with
the K-th element of the list.
Python3
# initializing list
test_list = [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': [7, 3, 9, 1]}]
# printing original list
print("The original list is : " + str(test_list))
# initializing K and key
K=2
key = "gfg"
# using for loop and try-except block
for d in test_list:
try:
if isinstance(d[key], list):
d[key] = d[key][K]
except KeyError:
pass
# printing result
print("The Modified Dictionaries : " + str(test_list))
Output
The original list is : [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg':
[7, 3, 9, 1]}]
The Modified Dictionaries : [{'gfg': 9, 'is': 8, 'good': 10}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg':
9}]
Time complexity: O(nm)
Where n is the number of dictionaries in the list and m is the maximum number of keys in any
dictionary. This is because we need to iterate over each dictionary in the list and check each key to
see if it matches the given key and whether the value is a list.
Auxiliary space: O(1)
Because we are not creating any additional data structures. We are only modifying the existing list in
place.
Method #5: Using map() function and lambda expression
Initialize the original list test_list with the given dictionaries.
Print the original list.
Initialize the index K with the given value. Initialize the key with the given value.
Use the map() function to modify the original list in place.
The map() function takes two arguments: a function and an iterable. In this case, the function is a
lambda expression that modifies each sub-dictionary in the list. The iterable is the original list itself.
The lambda expression checks if the value of the key is a list. If it is, then it updates the value of the
key to be the Kth index value of the list. Otherwise, it does nothing.
The map() function returns an iterator that applies the lambda function to each element of the list.
However, since we don’t need the iterator, we discard it using the list() function.
Print the modified list.
Python3
# Python3 code to demonstrate working of
# Replace value by Kth index value in Dictionary List
# Using map() + lambda
# initializing list
test_list = [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': [7, 3, 9, 1]}]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K=2
# initializing Key
key = "gfg"
# using map() function to modify the original list in-place
list(map(lambda sub: sub.update({key: sub[key][K]}) if isinstance(
sub[key], list) else None, test_list))
# printing result
print("The Modified Dictionaries : " + str(test_list))
Output
Python – Replace String by Kth Dictionary value
manjeet_04
Read
Discuss
Courses
Practice
Given a list of Strings, replace the value mapped with the Kth value of mapped list.
Input : test_list = [“Gfg”, “is”, “Best”], subs_dict = {“Gfg” : [5, 6, 7], “is” : [7, 4, 2]}, K = 0
Output : [5, 7, “Best”]
Explanation : “Gfg” and “is” is replaced by 5, 7 as 0th index in dictionary value list.
Input : test_list = [“Gfg”, “is”, “Best”], subs_dict = {“Gfg” : [5, 6, 7], “Best” : [7, 4, 2]}, K = 0
Output : [5, “is”, 7]
Explanation : “Gfg” and “Best” is replaced by 5, 7 as 0th index in dictionary value list.
Method #1: Using list comprehension
This is one of the ways in which this task can be performed. In this, we perform the task iteration
and conditional replacement inside a one-liner in list comprehension.
Python3
# Python3 code to demonstrate working of
# Replace String by Kth Dictionary value
# Using list comprehension
# initializing list
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {
"Gfg" : [5, 6, 7],
"is" : [7, 4, 2],
}
# initializing K
K=2
# using list comprehension to solve
# problem using one liner
res = [ele if ele not in subs_dict else subs_dict[ele][K]
for ele in test_list]
# printing result
print("The list after substitution : " + str(res))
Output
The original list : ['Gfg', 'is', 'Best']
The list after substitution : [7, 2, 'Best']
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using get() + list comprehension
The combination of above functions can be used to solve this problem. In this, we iterate using list
comprehension and check for key existence and substitution using get().
Python3
# Python3 code to demonstrate working of
# Replace String by Kth Dictionary value
# Using get() + list comprehension
# initializing list
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {
"Gfg" : [5, 6, 7],
"is" : [7, 4, 2],
# initializing K
K=2
# using list comprehension to solve problem using one liner
# get() to perform presence checks and assign default value
res = [subs_dict.get(ele, ele) for ele in test_list]
res = [ele[K] if isinstance(ele, list) else ele for ele in res]
# printing result
print("The list after substitution : " + str(res))
Output
The original list : ['Gfg', 'is', 'Best']
The list after substitution : [7, 2, 'Best']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using a loop
Use a for loop to iterate through the list and check if the current element is present in the subs_dict.
If it is, then replace the current element with the Kth value from the dictionary.
Python3
# initializing list
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {
"Gfg" : [5, 6, 7],
"is" : [7, 4, 2],
# initializing K
K=2
# using for loop to solve problem
for i in range(len(test_list)):
if test_list[i] in subs_dict:
test_list[i] = subs_dict[test_list[i]][K]
# printing result
print("The list after substitution : " + str(test_list))
Output
The original list : ['Gfg', 'is', 'Best']
The list after substitution : [7, 2, 'Best']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using map() function
Another way to replace the strings in a list with the k-th value from the dictionary is to use the map()
function, which takes a function and an iterable as arguments and applies the function to each
element of the iterable.
Here’s how you can use map() to solve this problem:
Define a function replace_string that takes a string s as input and returns either the value at the k-th
index of the dictionary if the string is a key in the dictionary, or the original string if it is not.
Use the map() function to apply replace_string to each element of the list test_list.
Convert the result of the map() function back to a list using the list() function.
Print the resulting list.
Python3
# Python3 code to demonstrate working of
# Replace String by Kth Dictionary value
# Using map() function
# initializing list
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {
"Gfg" : [5, 6, 7],
"is" : [7, 4, 2],
# initializing K
K=2
# define function to replace string
def replace_string(s):
return subs_dict[s][K] if s in subs_dict else s
# using map() function to solve problem
res = list(map(replace_string, test_list))
# printing result
print("The list after substitution : " + str(res))
Output
The original list : ['Gfg', 'is', 'Best']
The list after substitution : [7, 2, 'Best']
Time complexity: O(n), where n is the length of the input list test_list since we need to apply the
replace_string function to each element of the list.
Auxiliary space: O(n), since we create a new list res with the same length as test_list to store the
result.
Method #7: Using a dictionary comprehension
Step-by-step approach:
Use a dictionary comprehension to replace each string in test_list with its Kth element in subs_dict,
if the string is present as a key in the dictionary, otherwise, leave the string unchanged.
Store the resulting list in the variable res.
Print the updated list res.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Replace String by Kth Dictionary value
# Using dictionary comprehension
# initializing list
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {
"Gfg" : [5, 6, 7],
"is" : [7, 4, 2],
# initializing K
K=2
# using dictionary comprehension to solve problem
res = [subs_dict[x][K] if x in subs_dict else x for x in test_list]
# printing result
print("The list after substitution : " + str(res))
# Time complexity: O(n), where n is the length of the input list
# Auxiliary space: O(n), since we are creating a new list of the same length as the input list.
Output
Python – Replace index elements with elements in Other List
manjeet_04
Read
Discuss
Courses
Practice
Sometimes, while working with Python data, we can have a problem in which we have two lists and
we need to replace positions in one list with the actual elements from other list. Lets discuss certain
ways in which this task can be performed.
Method #1 : Using list comprehension This is one way to solve this problem. In this we just iterate
through the list and assign the index value from one list to other.
Python3
# Python3 code to demonstrate
# Replace index elements with elements in Other List
# using list comprehension
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace index elements with elements in Other List
# using list comprehension
res = [test_list1[idx] for idx in test_list2]
# printing result
print ("The lists after index elements replacements is : " + str(res))
Output :
The original list 1 is : [‘Gfg’, ‘is’, ‘best’] The original list 2 is : [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0] The lists
after index elements replacements is : [‘Gfg’, ‘is’, ‘best’, ‘is’, ‘Gfg’, ‘Gfg’, ‘Gfg’, ‘best’, ‘is’, ‘is’, ‘best’,
‘Gfg’]
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #2 : Using map() + lambda The combination of above functions can be used to perform this
task. In this, we perform task of extension of logic to every element using map() and lambda
functions.
Python3
# Python3 code to demonstrate
# Replace index elements with elements in Other List
# using map() + lambda
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace index elements with elements in Other List
# using map() + lambda
res = list(map(lambda idx: test_list1[idx], test_list2))
# printing result
print ("The lists after index elements replacements is : " + str(res))
Output :
The original list 1 is : [‘Gfg’, ‘is’, ‘best’] The original list 2 is : [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0] The lists
after index elements replacements is : [‘Gfg’, ‘is’, ‘best’, ‘is’, ‘Gfg’, ‘Gfg’, ‘Gfg’, ‘best’, ‘is’, ‘is’, ‘best’,
‘Gfg’]
Time complexity: O(M^N) as the number of combinations generated is M choose N.
Auxiliary space: O(M^N) as the size of the resultant list is also M choose N.
# Method #3 : Using numpy.take()
We can also perform this task by using numpy module. In this, we just have to pass the both list to
numpy.take() and then assign the result to list.
Python3
# Python3 code to demonstrate
# Replace index elements with elements in Other List
# using numpy.take()
# import numpy
import numpy as np
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace index elements with elements in Other List
# using numpy.take()
res = np.take(test_list1, test_list2)
# printing result
print ("The lists after index elements replacements is : " + str(res))
Output :
The original list 1 is : [‘Gfg’, ‘is’, ‘best’]
The original list 2 is : [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
The lists after index elements replacements is : [‘Gfg’, ‘is’, ‘best’, ‘is’, ‘Gfg’, ‘Gfg’, ‘Gfg’, ‘best’, ‘is’, ‘is’,
‘best’, ‘Gfg’]
Time complexity: O(n)
Auxiliary Space: O(n)
Method #4: using a for loop and a dictionary
Python3
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Create a dictionary to map indices to elements in test_list1
index_map = {index: element for index, element in enumerate(test_list1)}
# Replace index elements with elements in Other List using a for loop
res = [index_map[idx] for idx in test_list2]
# printing result
print ("The lists after index elements replacements is : " + str(res))
#This code is contributed by Vinay Pinjala.
Output
The original list 1 is : ['Gfg', 'is', 'best']
The original list 2 is : [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
The lists after index elements replacements is : ['Gfg', 'is', 'best', 'is', 'Gfg', 'Gfg', 'Gfg', 'best', 'is', 'is',
'best', 'Gfg']
Time complexity: O(n)
Auxiliary Space: O(n)
Method #5: Using pandas library
step-by-step algorithm for implementing the approach
Import the pandas module.
Define the two original lists.
Create a DataFrame object with one column containing the values from the first list.
Use the loc[] function of the DataFrame to extract the values from the first list corresponding to the
indices in the second list.
Convert the resulting series object to a list.
Assign the resulting list to a new variable.
Print the resulting list.
Python3
import pandas as pd
# Initializing the two lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# Creating a dataframe with one column ('a') containing the values from test_list1
df = pd.DataFrame({'a': test_list1})
# Extracting the values from test_list1 corresponding to the indices in test_list2
# by using the loc[] function of the dataframe and converting the result to a list
res = df.loc[test_list2, 'a'].tolist()
# Printing the resulting list
print("The lists after index elements replacements is : " + str(res))
output
The lists after index elements replacements is : ['Gfg', 'is', 'best', 'is', 'Gfg', 'Gfg', 'Gfg', 'best', 'is', 'is',
'best', 'Gfg']
Time complexity: O(n)
Space complexity: O(n)
Method #5 : Using zip() function
Use the zip() function to combine test_list1 and test_list2 element-wise.
Loop through the resulting tuples obtained in step 1.
Append the corresponding element from test_list1 to a new list res.
Print the final result list res.
Python3
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Using zip() function
res = [test_list1[i] for i in test_list2]
# printing result
print ("The lists after index elements replacements is : " + str(res))
#This code is contributed by Vinay Pinjala.
Python – Combine two dictionaries having key of the first dictionary and value of the second
dictionary
manjeet_04
Read
Discuss
Courses
Practice
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}
Explanation : Similar index keys' values assigned to dictionary 1.
Input : test_dict1 = {"Gfg" : 20, "best" : 100}, test_dict2 = {"Gfg2" : 26, "best2" : 70}
Output : {'Gfg': 26, 'best': 70}
Explanation : Similar index keys' values assigned to dictionary 1.
Method #1 : Using loop + keys()
This is one way in which this task can be performed. In this, we extract all the keys using keys() and
then assign required values inside loop.
Step-by-step approach :
Extract the keys from test_dict1 using the keys() method, and store them in a list called keys1.
Extract the values from test_dict2 using the values() method, and store them in a list called vals2.
Initialize an empty dictionary called res.
Loop through the range of the length of keys1.
For each iteration, assign the value of the idx-th element in keys1 as a key, and the value of the idx-
th element in vals2 as the value to the res dictionary.
Print the final mapped dictionary, res.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Assign similar index values in Dictionary
# Using loop + keys()
# initializing dictionaries
test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}
test_dict2 = {"Gfg2" : 26, "is2" : 19, "best2" : 70}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# extracting keys and values
keys1 = list(test_dict1.keys())
vals2 = list(test_dict2.values())
# assigning new values
res = dict()
for idx in range(len(keys1)):
res[keys1[idx]] = vals2[idx]
# printing result
print("Mapped dictionary : " + str(res))
Output
The original dictionary 1 is : {'Gfg': 20, 'is': 36, 'best': 100}
The original dictionary 2 is : {'Gfg2': 26, 'is2': 19, 'best2': 70}
Mapped dictionary : {'Gfg': 26, 'is': 19, 'best': 70}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using zip() + values()
This is yet another way in which this task can be performed. In this, we perform the task of mapping
using zip(), extracting values using values().
Step-by-step approach:
Initialize two dictionaries test_dict1 and test_dict2.
Print the original dictionaries.
Use the zip() function to combine the keys of test_dict1 with the values of test_dict2 and create a
new dictionary.
Print the resulting dictionary.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Assign similar index values in Dictionary
# Using zip() + values()
# initializing dictionaries
test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}
test_dict2 = {"Gfg2" : 26, "is2" : 19, "best2" : 70}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# using zip() to perform required dict. mapping
res = dict(zip(test_dict1, test_dict2.values()))
# printing result
print("Mapped dictionary : " + str(res))
Output
The original dictionary 1 is : {'Gfg': 20, 'is': 36, 'best': 100}
The original dictionary 2 is : {'Gfg2': 26, 'is2': 19, 'best2': 70}
Mapped dictionary : {'Gfg': 26, 'is': 19, 'best': 70}
Time complexity: O(n)
Auxiliary space: O(n) (for the resultant dictionary)
Method #3: Using enumerate() and loop:
we loop through the keys of the first dictionary using enumerate(), which gives us an index and the
key itself on each iteration. We then check if the index is within the range of the second dictionary’s
values (to avoid an index out of range error), and if so, we assign the corresponding value from the
second dictionary to the new dictionary using the current key. Finally, we print the resulting
dictionary.
Python3
# initializing dictionaries
test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}
test_dict2 = {"Gfg2" : 26, "is2" : 19, "best2" : 70}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# assigning new values
res = dict()
for idx, key in enumerate(test_dict1.keys()):
if idx < len(test_dict2):
res[key] = list(test_dict2.values())[idx]
# printing result
print("Mapped dictionary : " + str(res))
Output
The original dictionary 1 is : {'Gfg': 20, 'is': 36, 'best': 100}
The original dictionary 2 is : {'Gfg2': 26, 'is2': 19, 'best2': 70}
Mapped dictionary : {'Gfg': 26, 'is': 19, 'best': 70}
Time complexity: O(n)
Auxiliary space: O(n)
Method #4: Using dictionary comprehension and zip()
Use a dictionary comprehension to create a new dictionary with the same keys as test_dict1 and the
values from test_dict2. We do this by using the zip() function to iterate over both dictionaries
simultaneously, extracting the keys from test_dict1 and the values from test_dict2. Finally, we use
dictionary comprehension to create the new dictionary res with the key-value pairs.
Python3
# initializing dictionaries
test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}
test_dict2 = {"Gfg2" : 26, "is2" : 19, "best2" : 70}
# using dictionary comprehension and zip to assign new values
res = {k: v2 for k, v2 in zip(test_dict1.keys(), test_dict2.values())}
# printing result
print("Mapped dictionary : " + str(res))
Output
Mapped dictionary : {'Gfg': 26, 'is': 19, 'best': 70}
Time complexity: O(n)
Auxiliary space: O(n)
Method #5: Using dictionary comprehension and items()
Use dictionary comprehension along with the items() method to extract the key-value pairs from
both dictionaries simultaneously. The zip() function is used to pair up the corresponding key-value
pairs from both dictionaries. The resulting pairs are then used in the dictionary comprehension to
create a new dictionary with the keys from the first dictionary and values from the second
dictionary. This method has a time complexity of O(n), where n is the size of the dictionaries.
Approach:
Initialize a dictionary named “test_dict” with some key-value pairs.
Print the original dictionary using the “print()” function and string concatenation.
Initialize a variable “K” with the number of items to be returned from the dictionary.
Initialize an empty dictionary named “res”.
Use a for loop with “test_dict.items()” to iterate over the key-value pairs of the dictionary.
Check if the length of “res” is less than “K”. If so, add the key-value pair to the “res” dictionary using
the key as the index and the value as the value.
If the length of “res” is equal to or greater than “K”, break out of the loop.
Print the final dictionary named “res” limited to the first K items.
Python3
# Python3 code to demonstrate working of
# Assign similar index values in Dictionary
# Using dictionary comprehension and items()
# initializing dictionaries
test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}
test_dict2 = {"Gfg2" : 26, "is2" : 19, "best2" : 70}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# assigning new values using dictionary comprehension and items()
res = {k: v2 for (k, v1), (k2, v2) in zip(test_dict1.items(), test_dict2.items())}
# printing result
print("Mapped dictionary : " + str(res))