Snowflake Note
Snowflake Note
Snowflake Note
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.
Python3
print(Dict)
Output:
Creating a Dictionary
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be treated
distinctly.
Python3
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
Output:
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by
just placing to curly braces{}.
Python3
Dict = {}
print(Dict)
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
Output:
Empty Dictionary:
{}
Space complexity: O(n)
Nested Dictionary
Python3
print(Dict)
Output:
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
Dict = {}
print(Dict)
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print(Dict)
# to a single Key
Dict['Value_set'] = 2, 3, 4
print(Dict)
Dict[2] = 'Welcome'
print(Dict)
print(Dict)
Output:
Empty Dictionary:
{}
Time complexity: O(1)/O(n)
Space complexity: O(1)
In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets.
Python3
# Creating a Dictionary
print(Dict[1])
Output:
For
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.
Time complexity: O(1)
Space complexity: O(1)
Python3
# Creating a Dictionary
# method
print(Dict.get(3))
Output:
Geeks
In order to access the value of any key in the nested dictionary, use indexing [] syntax.
Python3
# Creating a Dictionary
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
Output:
{1: 'Geeks'}
Geeks
For
The items of the dictionary can be deleted by using the del keyword as given below.
Python3
# Creating a Dictionary
print("Dictionary =")
print(Dict)
del(Dict[1])
print(Dict)
Output
Dictionary ={1: 'Geeks', 'name': 'For', 3: 'Geeks'}
Dictionary methods
Method Description
dict.items() Returns a list containing a tuple for each 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.get(key, default = “None”) used to get the value specified for the passed key.
Python3
# demo for all dictionary methods
# 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:
{}
Python
dict_keys([1, 2, 3, 4])
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.
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.
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.
Python3
for x in lst[:-2]:
dct.update({lst[-2]: lst[-1]})
def convert_nested(dct):
result = dict()
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}
# dictionary splitting_dict_keys
Output
final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks':
{'for': 7}}}
Time Complexity: O(n)
Auxiliary Space: O(n)
Python3
def nest_dict(dict1):
result = {}
for k, v in dict1.items():
split_rec(k, v, result)
return result
# splitting keys in dict
if rest:
else:
out[k] = v
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
Output
final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks':
{'for': 7}}}
Python3
d = tree()
def default_to_regular(d):
return d
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
# iterating_over_dict
for k, v in ini_dict.items():
getFromDict(d, keys)[final_key] = v
Output
final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks':
{'for': 7}}}
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.
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.
Python3
if len(keys) == 1:
# base case: add value to the last key in the list
nested_dict[keys[0]] = value
else:
nested_dict[keys[0]] = {}
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
d = {}
# iterating_over_dict
for k, v in ini_dict.items():
# splitting keys
keys = k.split('_')
add_to_nested_dict(d, keys, v)
Output
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.
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.
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.
Python3
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}
d = {}
# iterating_over_dict
for k, v in ini_dict.items():
keys = k.split('_')
add_to_nested_dict(d, keys, v)
Output
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.
Similar Reads
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.
Nested loops are the logical structure in computer programming and coding. In which one loop
statement is inside another loop statement.
Syntax:
statements(iter_2)
statements(iter_1)
Loops have the ability to iterate over the items of any sequence, such as a list or a string.
Syntax:
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
start = time.time()
loop(i)
start = time.time()
nested(i)
print()
Output:
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.
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.
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.
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 calls the flatten_dict function on the ini_dict dictionary and prints the resulting flattened
dictionary.
Python3
# initialising_dictionary
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.
Python3
items = []
for k, v in d.items():
else:
items.append((new_key, v))
return dict(items)
# initialising_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']}
# Expected Output
for k in pyobj:
else:
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.
Define a function “flatten_dict” that takes in three parameters: dd (a dictionary), separator (a string,
default value “_”), and prefix (a string, default value “”).
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.
Python3
res = {}
else:
return res
# initialising_dictionary
res = flatten_dict(ini_dict)
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.
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.
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.
Python3
for x in lst[:-2]:
dct.update({lst[-2]: lst[-1]})
def convert_nested(dct):
result = dict()
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}
# dictionary splitting_dict_keys
Output
final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks':
{'for': 7}}}
Time Complexity: O(n)
Auxiliary Space: O(n)
Python3
def nest_dict(dict1):
result = {}
for k, v in dict1.items():
split_rec(k, v, result)
return result
# splitting keys in dict
if rest:
else:
out[k] = v
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
Output
final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks':
{'for': 7}}}
Python3
d = tree()
def default_to_regular(d):
return d
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
# iterating_over_dict
for k, v in ini_dict.items():
getFromDict(d, keys)[final_key] = v
Output
final_dictionary {'Geeks': {'for': {'for': 1, 'geeks': 4}}, 'for': {'geeks': {'Geeks': 3}}, 'geeks': {'Geeks':
{'for': 7}}}
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.
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.
Python3
if len(keys) == 1:
# base case: add value to the last key in the list
nested_dict[keys[0]] = value
else:
nested_dict[keys[0]] = {}
# initialising_dictionary
ini_dict = {'Geeks_for_for':1,'Geeks_for_geeks':4,
'for_geeks_Geeks':3,'geeks_Geeks_for':7}
d = {}
# iterating_over_dict
for k, v in ini_dict.items():
# splitting keys
keys = k.split('_')
add_to_nested_dict(d, keys, v)
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 :
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”.
Python3
# Using loops
# initializing dictionary
print(sub)
Output :
The original dictionary is : {'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}}
gfg
remark : good
rate : 5
cs
rate : 3
Time Complexity: O(n)
Auxiliary Space: O(1)
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.
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
Output
The original dictionary is : {'gfg': {'rate': 5, 'remark': 'good'}, 'cs': {'rate': 3}}
"gfg": {
"rate": 5,
"remark": "good"
},
"cs": {
"rate": 3
Time Complexity: O(n)
Auxiliary Space: O(1)
Python3
res = ""
for k, v in d.items():
else:
return res
print(pretty_print_dict(test_dict))
Output
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.
Approach
for loop to iterate over the keys and values of the dictionary.
Algorithm
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.
Python3
def pretty_print_dict(d):#define d
for value in v:
print(pretty_print_dict(d))#print output
Output
gfg:
remark: good
rate: 5
cs:
rate: 3
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 pprint
pprint.pprint(test_dict)
Output
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.
Step-by-step approach:
Python3
import json
# Initializing dictionary
print(pretty_print_dict)
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
import collections
print('Regular dictionary:')
for k, v in d.items():
print(k, v)
print('\nOrderedDict:')
d = collections.OrderedDict()
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.
Example:
Python
print("Before deleting:\n")
d = {}
print("Regular dictionary:")
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
print(key, value)
od = OrderedDict()
print("\nOrdered dictionary:")
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
print(key, value)
print("\nAfter deleting:\n")
print("Regular dictionary:")
d.pop('c')
print(key, value)
print("\nOrdered dictionary:")
od.pop('c')
print(key, value)
print("\nAfter re-inserting:\n")
print("Regular dictionary:")
d['c'] = 3
print(key, value)
print("\nOrdered dictionary:")
od['c'] = 3
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.
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 :
Pass the output of zip() to the dict() function to create a dictionary from the key-value pairs
generated by zip().
Python3
# initialization Dictionary
# printing result
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)
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’.
Python3
# Using dict.fromkeys()
# initialization Dictionary
# Using dict.fromkeys()
# printing result
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}}
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
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}}
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
# Using loop
# initializing dictionaries
# Using loop
test_dict1[key] = test_dict2[key]
# printing result
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
# initializing dictionaries
# printing result
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.
Python3
# Using loop
# initializing dictionaries
# Using loop
test_dict1.update(test_dict2)
# printing result
Output
Use the “**” operator to combine the dictionaries into a new dictionary:
The output should show the updated dictionary with the combined key-value pairs:
Example:
Python3
# 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
Output
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
# initializing dictionaries
new_dict = dict(test_dict1)
new_dict.update(test_dict2)
# printing result
Output
Time complexity: O(N), where N is the total number of key-value pairs in both dictionaries.
Auxiliary space: O(N)
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.
Python3
# initializing dictionaries
# printing result
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.
Step-by-step approach
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.
Python3
# initializing dictionary
# initializing K
K=3
# printing result
Output :
Python3
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# initializing K
K=3
# printing result
Output :
Step-by-step approach:
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.
Python3
# initializing dictionary
# initializing K
K=3
res = {}
res[key] = val
# printing result
Output
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.
Python3
# initializing dictionary
# initializing K
K=3
# printing result
Output
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.
Step-by-step approach:
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.
Python3
# initializing dictionary
# initializing K
K=3
res = dict(filter(lambda item: not(isinstance(item[1], int) and item[1] <= K), test_dict.items()))
# printing result
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.
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
# initializing dictionary
# printing result
Output
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
# using set.intersection()
# initializing dictionary
# using set.intersection()
temp = list(set(select_list).intersection(test_dict))
# printing result
Output
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.
Initialize a list called select_list with some keys from the dictionary.
Create an empty list called res to store the selected values from the dictionary.
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
# initializing selective list keys
res = []
res.append(test_dict[key])
# printing result
Output
Time Complexity: O(n)
Auxiliary Space: O(n)
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
# printing result
Output
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.
Step-by-step approach:
Define a recursive function that takes the dictionary and the list of keys as parameters.
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.
Python3
# defining the recursive function
return []
key = keys[0]
# if the key is in the dictionary, add its value to the result list
res = [dictionary[key]]
else:
res = []
# recursively call the function with the remaining keys in the list
return res
# initializing dictionary
# printing selective list
# calling the recursive function to get the values for the selected keys
# printing result
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.
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.
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.
Python3
# on certain criteria
# Initialising dictionary
print("resultant dictionary : ", str(result))
Output
Python3
# on certain criteria
# Initialising dictionary
result = dict(result)
Output
Python3
# Python code to demonstrate
# on certain criteria
# Initialising dictionary
res = dict()
for i in ini_dict:
if(str(ini_dict[i]).find("-") != 0):
res[i] = ini_dict[i]
Output
The time complexity of this code is O(n), where n is the number of items in the initial dictionary
ini_dict.
Here is an example of using map() and a custom function to filter negative values from a dictionary:
Python3
def filter_negative(item):
key, value = item
return
#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
print(result)
Output
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.
Python3
# on certain criteria
# Initialising dictionary
res = dict()
for i in list(ini_dict.keys()):
x=str(ini_dict[i])
if(not x.startswith("-")):
res[i]=ini_dict[i]
Output
Step-by-step approach:
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.
Python3
# Python code to demonstrate
# on certain criteria
# Initialising dictionary
Read
Discuss
Courses
Practice
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.
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.
High Pass Filtering: It eliminates low-frequency regions while retaining or enhancing the high-
frequency components. A high pass filtering mask is as shown.
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.
Averaging Filter:
Python3
import cv2
import numpy as np
img = cv2.imread('sample.png', 0)
# Obtain number of rows and columns
# of the image
m, n = img.shape
mask = mask / 9
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
import cv2
import numpy as np
img_noisy1 = cv2.imread('sample.png', 0)
# of the image
m, n = img_noisy1.shape
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 = 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.
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
# initializing dictionary
"all geeks"}
# initializing limit
limit = 4
# cutting chunks of K
# printing result
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(n)
Auxiliary Space: O(n)
Step-by-step approach:
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.
Python3
# initializing dictionary
"all geeks"}
# initializing limit
limit = 4
res = {}
# split value into chunks of size limit using string slicing
# loop through each chunk and add it to res with a new key
res[len(res)+1] = chunk
# printing result
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 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.
Step-by-step approach:
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.
Python3
# initializing dictionary
"all geeks"}
# initializing limit
limit = 4
res = {}
start = 0
res[len(res) + 1] = value[start:end]
start = end
# printing result
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(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.
Step-by-step approach:
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.
Python3
# initializing dictionary
"all geeks"}
# initializing limit
limit = 4
res = {}
# 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
res[i+1] = chunk
# printing result
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.
Step-by-step approach:
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.
Python3
# initializing dictionary
# initializing limit
limit = 4
res = {}
if remainder:
num_chunks += 1
# split value into chunks of size limit using string slicing
# loop through each chunk and add it to res with a new key
res[len(res)+1] = chunk
# printing result
Output
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.
Python3
# initializing dictionary
# 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]}
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
# initializing dictionary
res = list(sorted(set(chain(*test_dict.values()))))
# printing result
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 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.
Python3
# initializing dictionary
x=[]
for i in test_dict.keys():
x.extend(test_dict[i])
x=list(set(x))
x.sort()
# printing result
Output
The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2, 5]}
Python3
# initializing dictionary
x=list(test_dict.values())
y=[]
res=[]
for i in x:
y.extend(i)
for i in y:
res.append(i)
res.sort()
# printing result
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)
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.
Python3
# initializing dictionary
valuesList = []
freq = Counter(valuesList)
uniqueValues = list(freq.keys())
uniqueValues.sort()
# printing result
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 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.
STEPS:
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.
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.
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.
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.
import operator as op
# initializing dictionary
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
Output
The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2, 5]}
Time Complexity:O(N)
Method 7: Using set() + sum()
Python3
#initializing dictionary
#printing result
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.
Step-by-step approach
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.
Python3
# initializing dictionary
# initializing K
K=3
# printing result
Output :
Python3
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# initializing K
K=3
# printing result
Output :
Step-by-step approach:
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.
Python3
# initializing dictionary
# initializing K
K=3
res = {}
res[key] = val
# printing result
Output
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.
Python3
# initializing dictionary
# initializing K
K=3
# printing result
Output
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.
Step-by-step approach:
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.
Python3
# initializing dictionary
# initializing K
K=3
res = dict(filter(lambda item: not(isinstance(item[1], int) and item[1] <= K), test_dict.items()))
# printing result
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.
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
# Using loop
# initializing dictionary
# initializing updict
for sub in test_dict:
test_dict[sub] = updict[sub]
# printing result
Output
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
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
# initializing dictionary
# initializing updict
# printing result
Output
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
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
# initializing dictionary
# initializing updict
# printing result
Output
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
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
updated_values = map(
updated_values = map(
Output
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.
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:
Python3
default_dict[key] = value
updated_dict = dict(default_dict)
Read
Discuss
Courses
Practice
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
# initializing dictionary
# printing result
print("The ordered keys and values : " + str(res))
Output
Time Complexity: O(n)
Auxiliary Space: O(n)
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
# initializing dictionary
# printing result
Output
Python3
#( In order ) in dictionary
# initializing dictionary
a = list(test_dict.keys())
b = list(test_dict.values())
a.extend(b)
res = a
# printing result
Output
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
# using the zip() function and list comprehension to append dictionary keys and values
# printing result
Output
The ordered keys and values : [(1, 'Gfg'), (3, 'is'), (2, 'Best')]
Step-by-step approach:
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
# initializing dictionary
keys = sorted(test_dict.keys())
# printing result
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.
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
# Using loop
# initializing dictionary
# initializing updict
for sub in test_dict:
test_dict[sub] = updict[sub]
# printing result
Output
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
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
# initializing dictionary
# initializing updict
# printing result
Output
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
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
# initializing dictionary
# initializing updict
# printing result
Output
The updated dictionary: {'Gfg': 10, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 9}
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
updated_values = map(
updated_values = map(
Output
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.
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:
Python3
default_dict[key] = value
updated_dict = dict(default_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.
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.
Use isinstance() to check for list type of values and loop is used to iterate through dictionaries.
Step-by-step approach :
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.
Python3
# initializing list
test_list = [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10},
# initializing K
K=2
# initializing Key
key = "gfg"
sub[key] = sub[key][K]
# printing result
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)
In this, we reconstruct dictionaries with modified dictionary values using isinstance() and dictionary
comprehension is used to form intermediate dictionaries.
Python3
# initializing list
# initializing K
K=2
# initializing Key
key = "gfg"
res = [{newkey: (val[K] if isinstance(val, list) and newkey == key else val)
# printing result
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)
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
K=2
key = "gfg"
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
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)
Python3
# initializing list
K=2
key = "gfg"
for d in test_list:
try:
d[key] = d[key][K]
except KeyError:
pass
# printing result
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.
Initialize the index K with the given value. Initialize the key with the given value.
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.
Python3
# initializing list
# initializing K
K=2
# initializing Key
key = "gfg"
# printing result
Output
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.
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
# initializing list
subs_dict = {
# initializing K
K=2
# printing result
Output
Time Complexity: O(n)
Auxiliary Space: O(1)
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
# initializing list
subs_dict = {
# initializing K
K=2
# printing result
Output
Time Complexity: O(n)
Auxiliary Space: O(n)
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
subs_dict = {
# initializing K
K=2
for i in range(len(test_list)):
test_list[i] = subs_dict[test_list[i]][K]
# printing result
Output
Time Complexity: O(n)
Auxiliary Space: O(n)
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.
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.
Python3
# initializing list
subs_dict = {
# initializing K
K=2
def replace_string(s):
# printing result
Output
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.
Step-by-step approach:
Python3
# initializing list
# initializing K
K=2
# printing result
# Auxiliary space: O(n), since we are creating a new list of the same length as the input list.
Output
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
# Initializing lists
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing result
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
# Initializing lists
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing result
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’]
Python3
# using numpy.take()
# import numpy
import numpy as np
# Initializing lists
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# using numpy.take()
# printing result
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’]
Python3
# Initializing lists
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# Replace index elements with elements in Other List using a for loop
# printing result
Output
The lists after index elements replacements is : ['Gfg', 'is', 'best', 'is', 'Gfg', 'Gfg', 'Gfg', 'best', 'is', 'is',
'best', 'Gfg']
Use the loc[] function of the DataFrame to extract the values from the first list corresponding to the
indices in the second list.
Python3
import pandas as pd
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})
# by using the loc[] function of the dataframe and converting the result to a list
output
The lists after index elements replacements is : ['Gfg', 'is', 'best', 'is', 'Gfg', 'Gfg', 'Gfg', 'best', 'is', 'is',
'best', 'Gfg']
# Initializing lists
test_list2 = [0, 1, 2, 1, 0, 0, 0, 2, 1, 1, 2, 0]
# printing result
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, "best" : 100}, test_dict2 = {"Gfg2" : 26, "best2" : 70}
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.
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.
Python3
# initializing dictionaries
keys1 = list(test_dict1.keys())
vals2 = list(test_dict2.values())
res = dict()
res[keys1[idx]] = vals2[idx]
# printing result
Output
Time Complexity: O(n)
Auxiliary Space: O(n)
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.
Use the zip() function to combine the keys of test_dict1 with the values of test_dict2 and create a
new dictionary.
Python3
# initializing dictionaries
# printing result
Output
Time complexity: O(n)
Auxiliary space: O(n) (for the resultant dictionary)
Python3
# initializing dictionaries
res = dict()
res[key] = list(test_dict2.values())[idx]
# printing result
Output
Time complexity: O(n)
Auxiliary space: O(n)
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
# printing result
Output
Time complexity: O(n)
Auxiliary space: O(n)
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:
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.
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
# initializing dictionaries
# printing result