Vikram Chiluka

Check if Dictionary is Empty

Python: Check if Dictionary is Empty

Dictionaries are Python’s implementation of an associative list, which is a data structure. A dictionary is a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

Examples:

Input:

dictionary = {"this": 100, "is": 200, "BTechGeeks": 300}

Output:

Dictionary is not empty

Input:

dictionary= { }

Output:

Dictionary is empty

Given a dictionary, the task is check if dictionary is empty or not.

Check if Dictionary is Empty

There are 2 ways to check if the dictionary is empty they are:

Method #1: Using if operator

A dictionary can be cast or converted to a bool variable in Python. If the dictionary is empty, it will be True; otherwise, it will be False.

We can now apply this concept by directly inserting a dictionary object into the if statement. If we pass the dictionary object into the if statement, it will be implicitly converted to a bool value. If the dictionary is empty, it returns True otherwise, it returns False.

Below is the implementation:

Example-1:

# given dictionary
dictionary = {"this": 100, "is": 200, "BTechGeeks": 300}

# checking if dictionary  is empty
if dictionary:
    print("Dictionary is not empty")
else:
    print("Dictionary is empty")

Output:

Dictionary is not empty

Example-2:

# given dictionary
dictionary = {}

# checking if dictionary  is empty
if dictionary:
    print("Dictionary is not empty")
else:
    print("Dictionary is empty")

Output:

Dictionary is empty

Method #2:Using len() function

When we pass the dictionary object to the len() function, we get the number of key-value pairs in the dictionary. So, we can use the len() function to determine whether or not the dictionary is empty.

If the length of dictionary is 0 then dictionary is empty otherwise not.

Below is the implementation:

Example -1:

# given dictionary
dictionary = {"this": 100, "is": 200, "BTechGeeks": 300}

# checking if dictionary  is empty using len() function
if len(dictionary) == 0:
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")

Output:

Dictionary is not empty

Example-2:

# given dictionary
dictionary = {}

# checking if dictionary  is empty using len() function
if len(dictionary) == 0:
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")

Output:

Dictionary is empty

Related Programs:

Iterate over dictionary with list values

Python: Iterate over Dictionary with List Values

Dictionaries are the implementation by Python of a data structure associative array. A dictionary is a collection of pairs of key values. A key pair and its associated value represent each key pair.

The list of key value pairs in curly braces that is separated by comma defines a dictionary. Column ‘:’ separates the value of each key.

A dictionary cannot be sorted only to get a representation of the sorted dictionary. Inherently, dictionaries are orderless, but not other types, including lists and tuples. Therefore, you need an ordered data type, which is a list—probably a list of tuples.

Given a dictionary with the values as list, the task is to iterate over the dictionary and print it.

Examples:

Input:

dictionary = {
'hello': [110, 200, 300],
'this': [3, 4, 5],
'is': 10,
'BTechGeeks': [1, 2, 3, 'python']
}

Output:

hello : 110 200 300 
this : 3 4 5 
is : 10 
BTechGeeks : 1 2 3 python

Traverse the dictionary with list values

We can traverse the dictionary by many ways two of them are

Method #1:Using nested for loop and exceptional handling

Approach:

  • Iterate over the keys of dictionary.
  • Now using nested for loop iterate over the values of keys.
  • If a key has only one value, we get an error, so handle those errors with exceptional handling in Python by printing the key’s single value.

Below is the implementation:

# given dictionary
dictionary = {
    'hello': [110, 200, 300],
    'this': [3, 4, 5],
    'is': 10,
    'BTechGeeks': [1, 2, 3, 'python']
}
# iterate through dictionary
for key in dictionary:
    print(key, end=" : ")
    try:
        for value in dictionary[key]:
            print(value, end=" ")
    except:
        print(dictionary[key], end=" ")
    print()

Output:

hello : 110 200 300 
this : 3 4 5 
is : 10 
BTechGeeks : 1 2 3 python

Method #2:Using List comprehension

In the preceding example, we iterated through all of the list values for each key. However, if you want a complete list of pairs, we can also use list comprehension. Because a key in our dictionary can have multiple values, for each pair we will generate a list of pairs where the key is the same but the value is different.

Below is the implementation:

# given dictionary
dictionary = {
    'hello': [110, 200, 300],
    'this': [3, 4, 5],
    'is': [2, 10, 45],
    'BTechGeeks': [1, 2, 3, 'python']
}
# using list comprehension
keyvaluepairs = [(key, value)
                 for key, values in dictionary.items()
                 for value in values]
# traverse and print key  value pairs
for i in keyvaluepairs:
    print(i)

Output:

('hello', 110)
('hello', 200)
('hello', 300)
('this', 3)
('this', 4)
('this', 5)
('is', 2)
('is', 10)
('is', 45)
('BTechGeeks', 1)
('BTechGeeks', 2)
('BTechGeeks', 3)
('BTechGeeks', 'python')

Related Programs:

Check if a String contains a Sub String Case Insensitive

Python : Check if a String contains a Sub String | Case Insensitive

Strings are one of the most commonly used types in Python. We can easily make them by enclosing characters in quotes. Python considers single quotes to be the same as double quotes. String creation is as easy as assigning a value to a variable.

Let’s look at different ways to solve the general problem of determining whether a specific piece of string is present in a larger string. This is a very common type of problem that every programmer encounters at least once in his or her career. This article discusses various methods for resolving it.

Given a string and substring ,the task is to check if the substring is present in given string.

Examples:

1)Case sensitive

Input:

string = 'This is BTechGeeks online platform'  substring = 'online'

Output:

Yes

2)Case insensitive

Input:

string = 'This is BTechGeeks Online platform'  substring = 'online'

Output:

Yes

Determine whether a String contains a Sub String

There are several ways to check whether a string contains given substring some of them are:

Method #1:Using in operator

The in operator is the most generic and fastest way to check for a substring in Python. The power of the in operator in Python is well known and is used in many operations throughout the language.

1)Case sensitive

Below is the implementation:

# given string
string = 'This is BTechGeeks online platform'
# given substring
substring = 'online'
# checking if the substring is present in string
if substring in string:
    print('Yes')
else:
    print('No')

Output:

Yes

2)Case Insensitive

We can check them by converting both given string and substring to lower case or uppercase.

Below is the implementation:

# given string
string = 'This is BTechGeeks Online platform'
# given substring
substring = 'online'
# checking if the substring is present in string by converting to lowercase
if substring.lower() in string.lower():
    print('Yes')
else:
    print('No')

Output:

Yes

Method #2: Using not in operator

Similarly, we can use the “not in” operator to test the opposite scenario, that is, to see if a string or character does not exist in another string.

1)Case sensitive

Below is the implementation:

# given string
string = 'This is BTechGeeks online platform'
# given substring
substring = 'online'
# checking if the substring is present in string
if substring not in string:
    print('No')
else:
    print('Yes')

Output:

Yes

2)Case insensitive

We can check them by converting both given string and substring to lower case or uppercase.

Below is the implementation:

# given string
string = 'This is BTechGeeks online platform'
# given substring
substring = 'online'
# checking if the substring is present in string by converting to lowercase
if substring.lower() not in string.lower():
    print('No')
else:
    print('Yes')

Output:

Yes

Method #3:Using str.find()

The str.find() method is generally used to get the lowest index at which the string occurs, but it also returns -1 if the string is not present; thus, if any value returns greater than zero, the string is present; otherwise, it is not present.

1)Case sensitive

Below is the implementation:

# given string
string = 'This is BTechGeeks online platform'
# given substring
substring = 'online'
# using find operator
result = string.find(substring)
# if result is greater than 0 then print yes
if result > 0:
    print('Yes')
else:
    print('No')

Output:

Yes

2)Case insensitive

We can check them by converting both given string and substring to lower case or uppercase.

Below is the implementation:

# given string to lower
string = 'This is BTechGeeks Online platform'.lower()
# given substring to lower
substring = 'online'.lower()
# using find operator
result = string.find(substring)
# if result is greater than 0 then print yes
if result > 0:
    print('Yes')
else:
    print('No')

Output:

Yes

Method #4:Using index() function

This method can be used to perform the same task as str.find(), but unlike str.find(), it does not return a value, but rather a ValueError if string is not present, so catching the exception is the only way to check for string in substring.

1)Case sensitive

Below is the implementation:

# given string
string = 'This is BTechGeeks Online platform'
# given substring
substring = 'online'
# using try and except
# using index function
try:
    result = string.find(substring)
    print('Yes')
except:
    print('No')

Output:

Yes

2)Case insensitive

We can check them by converting both given string and substring to lower case or uppercase.

Below is the implementation:

# given string to lower
string = 'This is BTechGeeks Online platform'.lower()
# given substring to lower
substring = 'online'.lower()
# using try and except
# using index function
try:
    result = string.find(substring)
    print('Yes')
except:
    print('No')

Output:

Yes

Related Programs:

map-function-with-examples

Python : map() Function with Examples

In this article, we will look at how to use map to transform the contents of an iterable sequence (). We’ll also go over how to use the map() function with lambda functions and how to use map() to transform a dictionary.

Map() function in Python

1)map() function details

Syntax:

map(function, iterable)

Parameters:

function :   It is a function to which each element of a given iterable is passed.
Iterable  :   It is an iterable that is to be mapped.

Return :

The map() feature applies to each item of an iterable function and returns the results list.

You can then pass the return value from map() (map object) to functions like list() (to create a list), set() (to create a set), etc.

2)Working of map function

In the given sequence, it iterates across all elements. It calls the given callback() function on every item and then stores the returned value in a new sequence during iteration of the sequence. Ultimately this new transformed element sequence will return.

Examples:

3)Squaring each list element using map

By writing a function that squares the number, we can square each list element.

Below is the implementation:

# function which squares the number
def squareNumber(number):
    # square the number
    return number*number


# given list
givenlist = [5, 2, 6, 9]
# using map function to square each list element
squarelist = list(map(squareNumber, givenlist))
# print squarelist
print(squarelist)

Output:

[25, 4, 36, 81]

4)Reverse each string in list

By writing a function which reverses the string, we can reverse each list element.

Below is the implementation:

# function which reverses the string
def revString(string):
    # reverse the string
    return string[::-1]


# given list
givenlist = ['hello', 'this', 'is', 'BTechGeeks']
# using map function to reverse each string in list
reverselist = list(map(revString, givenlist))
# print squarelist
print(reverselist)

Output:

['olleh', 'siht', 'si', 'skeeGhceTB']

5)Adding two lists

We can add two lists by using lambda function

Below is the implementation:

# given lists
list1 = [9, 3, 4]
list2 = [4, 8, 6]
# using map function to sum the two lists
sumlist = list(map(lambda a, b: a + b, list1, list2))
# print sumlist
print(sumlist)

Output:

[13, 11, 10]

 
Related Programs:

How to Sort a List of Tuples by second Item

Python: How to Sort a List of Tuples by second Item

Tuples are a type of variable that allows you to store multiple items in a single variable. Tuple is one of four built-in data types in Python that are used to store data collections. The other three are List, Set, and Dictionary, all of which have different qualities and applications. A tuple is a collection that is both ordered and immutable.

The task is to write a Python program that sorts tuples by the second item in each tuple given a list of tuples.

Examples:

Input:

giventuple = [('Hello', 400), ('this', 500), ('is', 200), ('BTechGeeks', 100)]

Output:

[('BTechGeeks', 100), ('is', 200), ('Hello', 400), ('this', 500)]

Python program for Sorting a List of Tuples by the Second item

1)Key Function

When sorting a list, all of the list’s elements are compared to one another. However, before comparing the entries, it will call the key function on each entry to determine which portion of the object will be compared.

In other words, when an element is passed to the key function, it returns the element that should be used to compare the elements in the list while sorting.

2)Using lambda function

To sort a list of tuples by the second or ith item, we must include our custom comparator, i.e. key function, in the  sort () function.

We use lambda function as key function.

Below is the implementation:

# given tuple
giventuple = [('Hello', 400), ('this', 500), ('is', 200), ('BTechGeeks', 100)]
# using lambda function
giventuple.sort(key=lambda elem: elem[1])
# print giventuple
print(giventuple)

Output:

[('BTechGeeks', 100), ('is', 200), ('Hello', 400), ('this', 500)]

3)Using custom function as comparator

First, create a function that accepts a tuple and returns the second element.

Below is the implementation:

def comparator(elementtuple):
    return elementtuple[1]


# given tuple
giventuple = [('Hello', 400), ('this', 500), ('is', 200), ('BTechGeeks', 100)]
# using lambda function
giventuple.sort(key=comparator)
# print giventuple
print(giventuple)

Output:

[('BTechGeeks', 100), ('is', 200), ('Hello', 400), ('this', 500)]

Related Programs:

Different ways to Create a Tuple and Iterate over it

Python Tuple: Different ways to Create a Tuple and Iterate over it

Tuples are a type of variable that allows you to store multiple items in a single variable. Tuple is one of four built-in data types in Python that are used to store data collections. The other three are List, Set, and Dictionary, all of which have different qualities and applications. A tuple is a collection that is both ordered and immutable.

In this post we are going to discuss different ways to create the tuple and traverse through it.

Create a Tuple and Traverse it

1)List vs Tuple

  • Lists and tuples are represented in slightly different ways. Lists are commonly surrounded by the square bracket [], and elements are separated by commas. Tuples are surrounded by parenthesis (), and elements are separated by a comma. The parenthesis is optional, and these tuples are known as tuple packing.
  • It is the most significant distinh3ction between a list and a tuple, with lists being mutable and tuples being immutable. Lists are mutable, which means that the Python object can be modified after it is created, whereas tuples cannot be modified after they are created.
  • Tuples support fewer operations than lists. The built-in dir(object) function is used to retrieve all of the list and tuple’s supported functions.

2)Create a tuple of various types of elements

We can make a tuple of different elements by separating them with ‘,’ and wrapping them in braces i.e ( ).

Below is the implementation:

# Tuple
newtuple = ('hello', 3.5, 'this', 200, 'is', True, 'BTechGeeks')
# print tuple
print(newtuple)

Output:

('hello', 3.5, 'this', 200, 'is', True, 'BTechGeeks')

3)Create a tuple out of unpacked elements

We can also create a tuple from unpacked elements i.e without any braces just elements separated by comma.

Below is the implementation:

# Tuple
newtuple = 'hello', 3.5, 'this', 200, 'is', True, 'BTechGeeks'
# print tuple
print(newtuple)

Output:

('hello', 3.5, 'this', 200, 'is', True, 'BTechGeeks')

4)Create empty tuple

We can create tuple directly using () symbol.

Below is the implementation:

# creating new tuple
newtuple = ()
# print tuple
print(newtuple)

Output:

()

5)Convert list to tuple

We can convert list to tuple by using the syntax tuple(list_name).

Below is the implementation:

# given list
givenlist = [100, 'hello', 4.5, 'BTechGeeks']
# converting this list to tuple
newtuple = tuple(givenlist)
# print new tuple
print(newtuple)

Output:

(100, 'hello', 4.5, 'BTechGeeks')

6)Traverse the tuple

We can iterate over the tuple using for loop.

Below is the implementation:

# Tuple
newtuple = ('hello', 3.5, 'this', 200, 'is', True, 'BTechGeeks')
# Traverse the tuple
for i in newtuple:
    print(i)

Output:

hello
3.5
this
200
is
True
BTechGeeks

Related Programs:

Python Set: remove() vs discard() vs pop()

A Python set is a list of things that are not in any particular order. – element in the set must be unique and immutable, and duplicate elements are removed from the sets. Sets are mutable, which means we can change them after they’ve been formed.

Unlike other Python sets, the elements of the set have no index, which means we can’t access any element of the set directly using the index. We may, however, print them all together or loop through the collection to get the list of elements.

Example:

Input:

givenset= {'This', 'is', 'BTechGeeks'} element='is'

Output:

{'BTechGeeks', 'this'}

Remove a element from the Set

There are several ways to remove a element from the set some of them are:

Method #1:Using discard() function

In Python, the built-in method discard() removes an element from a collection only if it is already present. If the element is missing from the list, no error or exception is thrown, and the original set is printed.
Implementing the discard() function if the element is present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'is'
# removing element which is in set using discard function.
givenset.discard(element)
# printing the set
print(givenset)

Output:

{'BTechGeeks', 'this'}

Implementing the discard() function if the element is not present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'hello'
# removing element which is not in set using discard function.
givenset.discard(element)
# printing the set
print(givenset)

Output:

{'is', 'this', 'BTechGeeks'}

Method #2:Using remove() function

In Python, the built-in method remove() removes an element from a set only if it is already present, similar to how the discard() method removes an element from a set. If the element is missing from the list, an error or exception is thrown.

Implementing the remove() function if the element is present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'is'
# removing element which is in set using remove() function.
givenset.remove(element)
# printing the set
print(givenset)

Output:

{'BTechGeeks', 'this'}

Implementing the remove() function if the element is not present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'hello'
# removing element which is not in set using remove() function.
givenset.remove(element)
# printing the set
print(givenset)

Output:

Traceback (most recent call last):
  File "/home/ebe45b71f9f465d547ea9cb944ebe071.py", line 6, in <module>
    givenset.remove(element)
KeyError: 'hello'

Method #3:Using pop() function

This operation takes an arbitrary element from the set and returns it.
It throws a KeyError if there are no elements to delete.

Implementing the pop() function if the element is present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# removing random element which is  in set using pop() function.
givenset.pop()
# printing the set
print(givenset)

Output:

{'is', 'BTechGeeks'}

 

 
Related Programs:

Python Set: Remove Single or Multiple Elements from a Set?

A Python set is a list of things that are not in any particular order. – element in the set must be unique and immutable, and duplicate elements are removed from the sets. Sets are mutable, which means we can change them after they’ve been formed.

Unlike other Python sets, the elements of the set have no index, which means we can’t access any element of the set directly using the index. We may, however, print them all together or loop through the collection to get the list of elements.

Examples:

Removing single element from the set

Input:

givenset= {'this', 'is', 'BTechGeeks'} element='is'

Output:

{'BTechGeeks', 'this'}

Removing multiple elements from the set

Input:

givenset= {'Hello' ,'this', 'is', 'BTechGeeks'} element=['is' , 'this ']

Output:

{'BTechGeeks', 'hello'}

Remove one or more elements from a set

There are several ways to remove one or more elements from a set some of them are:

Method #1:Using discard() function to remove single element

In Python, the built-in method discard() removes an element from a collection only if it is already present. If the element is missing from the list, no error or exception is thrown, and the original set is printed.

Implementing the discard() function if the element is present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'is'
# removing element which is in set using discard function.
givenset.discard(element)
# printing the set
print(givenset)

Output:

{'BTechGeeks', 'this'}

Implementing the discard() function if the element is not present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'hello'
# removing element which is not in set using discard function.
givenset.discard(element)
# printing the set
print(givenset)

Output:

{'is', 'this', 'BTechGeeks'}

Method #2:Using remove() function to remove single element

In Python, the built-in method remove() removes an element from a set only if it is already present, similar to how the discard() method removes an element from a set. If the element is missing from the list, an error or exception is thrown.

Implementing the remove() function if the element is present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'is'
# removing element which is in set using remove() function.
givenset.remove(element)
# printing the set
print(givenset)

Output:

{'BTechGeeks', 'this'}

Implementing the remove() function if the element is not present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# given element
element = 'hello'
# removing element which is not in set using remove() function.
givenset.remove(element)
# printing the set
print(givenset)

Output:

Traceback (most recent call last):
  File "/home/ebe45b71f9f465d547ea9cb944ebe071.py", line 6, in <module>
    givenset.remove(element)
KeyError: 'hello'

Method #3:Using pop() function to remove single element

This operation takes an arbitrary element from the set and returns it.
It throws a KeyError if there are no elements to delete.

Implementing the pop() function if the element is present in the set:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# removing random element which is  in set using pop() function.
givenset.pop()
# printing the set
print(givenset)

Output:

{'is', 'BTechGeeks'}

Method #4:Using difference_update() to remove multiple elements from the set

The Set class in Python has a function called difference update() that takes a sequence as an argument and removes all of the elements from the set. Let’s use this to remove all of the list’s elements from the set.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTechGeeks'}
# given list of elements to be deleted from set
elementslist = ['this', 'is']
# removing elements
givenset.difference_update(elementslist)
# printing the set
print(givenset)

Output:

{'BTechGeeks', 'hello'}

Method #5:Using discard() + for loop to remove multiple elements from set

Iterating over the elements to be removed and removing them one by one from the set  using discard() is another way to remove several elements from a set.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTechGeeks'}
# given list of elements to be deleted from set
elementslist = ['this', 'is']
# Traverse the elementslist which is to be deleted
for element in elementslist:
    # remove the element from set using discard
    givenset.discard(element)
# printing the set
print(givenset)

Output:

{'BTechGeeks', 'hello'}

Method #6:Using remove() + for loop to remove multiple elements from set

Iterating over the elements to be removed and removing them one by one from the set  using remove() is another way to remove several elements from a set.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTechGeeks'}
# given list of elements to be deleted from set
elementslist = ['this', 'is']
# Traverse the elementslist which is to be deleted
for element in elementslist:
    # remove the element from set using remove
    givenset.discard(element)
# printing the set
print(givenset)

Output:

{'hello', 'BTechGeeks'}

Related Programs:

Python : How to copy a dictionary | Shallow Copy vs Deep Copy

Dictionaries are Python’s implementation of an associative array data structure. A dictionary is a grouping of key-value pairs. Each key pair is represented by a key pair and its associated value.

A dictionary is defined by a list of key value pairs enclosed in curly braces and separated by a comma. The value of each key is separated by the column ‘:’.

It is not possible to sort a dictionary solely to obtain a representation of the sorted dictionary. Dictionary entries are ordered by default, but other data types, such as lists and tuples, are not. As a result, you’ll need an ordered data form like a list—most likely a list of tuples.

Examples:

Input:

dictionary = {'this': 200, 'is':100, 'BTechGeeks':300}

Output:

Old dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}
New dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}

Copy a Dictionary:

There are several ways to copy a dictionary some of them are:

Method #1:Using loop and copying element by element

This technique involves traversing the entire dictionary and copying each and every element pointed by the key to a previously declared new dictionary.

Approach:

  • Take a empty new dictionary.
  • Traverse the old dictionary using for loop.
  • Copy the key and value of old dictionary element by element.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# Take a empty dictionary
newdict = {}
# Traverse the old dictionary
for key in dictionary:
    newdict[key] = dictionary[key]
# print old dictionary
print("Old dictionary : ", dictionary)
# print new dictionary
print("New dictionary : ", newdict)

Output:

Old dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}
New dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}

Method #2: Using = operator

We can simply copy a dictionary using = operator.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# copying dictionary to new dictionary
newdict = dictionary
# print old dictionary
print("Old dictionary : ", dictionary)
# print new dictionary
print("New dictionary : ", newdict)

Output:

Old dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}
New dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}

Explanation:

  • We begin by creating a dictionary dictionary. And then use the code line newlist=dictionary to copy it to a new object dict2.
  • This procedure copies each object’s references from dictionary to the new dictionary newdict.
  • As a consequence, changing any aspect of newdict will change dictionary and vice versa.
    The above code shows that when we update any(iterable or non-iterable) object in newdict, the same change is seen in dictionary.

Method #3: Using copy() to create a shallow copy of dictionary

A shallow copy is when a new dictionary object is formed and references to existing dictionary objects are inserted into it.

In Python, the dictionary copy() method creates a shallow copy of the given dictionary. It’s identical to what we saw before when copying elements by traversing through a dictionary.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# copying dictionary to new dictionary using copy
newdict = dictionary.copy()
# updating new dictionary
newdict['hello'] = 400
# print old dictionary
print("Old dictionary : ", dictionary)
# print new dictionary
print("New dictionary : ", newdict)

Output:

Old dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}
New dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300, 'hello': 400}

Explanation:

  • We initialize the dictionary dictionary with any values. To make a shallow copy, use the copy() method on it.
  • We update the new elements and see the corresponding shift in the original dictionary after the copy is made.
  • Changes in non-iterable elements of newdict have no impact on the original dictionary, just as they do with the element-by-element copying technique.
  • The change is reflected in the given dictionary, dictionary, for iterable ones like lists.

Method #4: Using copy.deepcopy()  to copy a dictionary

In Python, the deepcopy() method is part of the copy module. It creates a new dictionary from the passed dictionary’s elements. This method recursively copies all of the elements of the given dictionary.

Below is the implementation:

# importing copy
import copy
# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# copying dictionary to new dictionary using deepcopy
newdict = copy.deepcopy(dictionary)
# updating new dictionary
newdict['hello'] = 400
# print old dictionary
print("Old dictionary : ", dictionary)
# print new dictionary
print("New dictionary : ", newdict)

Output:

Old dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300}
New dictionary :  {'this': 200, 'is': 100, 'BTechGeeks': 300, 'hello': 400}

Related Programs:

Python Dictionary: Values() Function

Python’s implementation of an associative array data structure is dictionaries. A dictionary is a collection of key/value pairs. A key pair and its associated value are used to represent each key pair.

A dictionary is a list of key-value pairs enclosed in curly braces and separated by commas. The column ‘:’ separates the value of each key.

Sorting a dictionary solely for the purpose of obtaining a representation of the sorted dictionary is not possible. By default, dictionary entries are ordered, but other data types, such as lists and tuples, are not. As a result, you’ll need an ordered data form, such as a list—probably a list of tuples.

Dictionary values() function & examples of it

values() is a built-in Python method that returns a list of all the values available in a given dictionary.

Syntax:

dictionary_name.values()

Parameters:

There is no need to pass parameters.

Return type:

It returns a sequence containing a view of all dictionary values. Because the sequence is just a view of values, any change to a value in the dictionary will be reflected in the sequence as well.

1)Display all the values of the dictionary

We can display all the values of the dictionary by using the given syntax above.

Implementation:

# given dictionary
dictionary = {'Hello': 700, 'This': 200, 'is': 100, 'BTechGeeks': 300}
# getting all the values from the given dictionary
dictvalues = dictionary.values()
# printing the values
print(dictvalues)

Output:

dict_values([700, 200, 100, 300])

2)Update/Modify the values of the dictionary

If we first fetch all of the dictionary’s values with the values() function and then modify the dictionary, the changes will be reflected in the sequence of the previously fetched values as well.

Below is the implementation:

# given dictionary
dictionary = {'Hello': 700, 'This': 200, 'is': 100, 'BTechGeeks': 300}
# getting all the values from the given dictionary
dictvalues = dictionary.values()
# print the values before modification
print("Before Modification", dictvalues)
# updating value of BTechGeeks to 1000
dictionary['BTechGeeks'] = 1000
# printing the after modification
print("After Modification", dictvalues)

Output:

Before Modification dict_values([700, 200, 100, 300])
After Modification dict_values([700, 200, 100, 1000])

3)Conversion of dictionary values to list

The sequence returned by the values() function can be passed to the list to create a list of all values in the dictionary .

We use list() function to achieve this

Below is the implementation:

# given dictionary
dictionary = {'Hello': 700, 'This': 200, 'is': 100, 'BTechGeeks': 300}
# getting all the values from the given dictionary and converting to list
dictvalues = list(dictionary.values())
# printing the dictionary values list
print(dictvalues)

Output:

[700, 200, 100, 300]

4)Display Maximum and minimum values

We can display maximum and minimum values by using max() and min() functions .

Below is the implementation:

# given dictionary
dictionary = {'Hello': 700, 'This': 200, 'is': 100, 'BTechGeeks': 300}
# getting all the values from the given dictionary and converting to list
dictvalues = dictionary.values()
# Getting max and min values
maxvalue = max(dictvalues)
minvalue = min(dictvalues)
# print the max value
print("Maximum value in dictionary", maxvalue)
print("Minimum value in dictionary", minvalue)

Output:

Maximum value in dictionary 700
Minimum value in dictionary 100

5)Display sum of dictionary values

We can display sum of dictionary values by using sum() function .

Below is the implementation:

# given dictionary
dictionary = {'Hello': 700, 'This': 200, 'is': 100, 'BTechGeeks': 300}
# getting all the values from the given dictionary and converting to list
dictvalues = dictionary.values()
# Getting sum of dictionary values
valuesum = sum(dictvalues)
# print sum of values
print("Sum of dictionary values", valuesum)

Output:

Sum of dictionary values 1300

6)Display Average of dictionary values

We can display average of dictionary values with the help of sum() and len() functions.

Below is the implementation:

# given dictionary
dictionary = {'Hello': 700, 'This': 200, 'is': 100, 'BTechGeeks': 300}
# getting all the values from the given dictionary and converting to list
dictvalues = dictionary.values()
# Getting average of dictionary values
averagevalue = sum(dictvalues)/len(dictvalues)
# print average of values
print("Average of dictionary values", averagevalue)

Output:

Average of dictionary values 325.0

Related Programs: