Vikram Chiluka

Python : How to Sort a Dictionary by Key or Value ?

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.

In this post, we will look at how to sort a dictionary by key or value

Examples:

By keys

Input:

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

Output:

BTechGeeks : 300
is : 100
this :200

Input:

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

Output:

is : 100
this : 200
BTechGeeks : 300

Sort a Dictionary by Key/Value

There are several ways to sort a dictionary by key or value some of them are:

Sort Dictionary by keys:

Method #1: Using items() function

A view object is returned by the items() method. The object view contains the dictionary’s key-value pairs as tuples in a list.

The object displays any modifications made in the dictionary.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list
for i in sorted(dictitems):
    # print key and value
    print(i[0], ":", i[1])

Output:

BTechGeeks : 300
is : 100
this :200

Method #2:Using dict.keys() method

  • Convert the keys of the dictionary to list .
  • Sort the list .
  • Print the corresponding keys and values as you traverse the list.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using dict.keys
dictlist = list(dictionary.keys())
# sort the list
dictlist.sort()
# Print the corresponding key and value by traversing this list
for key in dictlist:
    # print key and value
    print(key, ":", dictionary[key])

Output:

BTechGeeks : 300
is : 100
this :200

Method #3: Sorting the dictionary keys in reverse order

Both of the previous solutions sorted the dictionary ascending order by key. What if we were to sort the contents by the keys in decreasing order? This can be accomplished by simply passing an attribute to the sorted() function, such as reverse=True.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list in descending order
for i in sorted(dictitems, reverse=True):
    # print key and value
    print(i[0], ":", i[1])

Output:

this : 200
is : 100
BTechGeeks : 300

Sort Dictionary by Values:

Using sorted() and items() functions to sort dictionary by value

We’ll use the same sorted() function and transfer a key function that returns the first index element of the tuple, i.e. the value field from the key/value pair, to sort dictionary elements by value.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list in
# using key to sort by values
for i in sorted(dictitems, key=lambda x: x[1]):
    # print key and value
    print(i[0], ":", i[1])

Output:

is : 100
this : 200
BTechGeeks : 300

Using sorted() + items() +reverse() functions to sort dictionary by value in reverse order

This can be accomplished by simply passing an attribute to the sorted() function, such as reverse=True.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list in
# using key to sort by values
for i in sorted(dictitems, key=lambda x: x[1], reverse=True):
    # print key and value
    print(i[0], ":", i[1])

Output:

BTechGeeks : 300
this : 200
is : 100

Related Programs:

Python: Check if String is Empty or Contain Spaces only

Python strings are byte arrays representing characters of Unicode.. However, because Python lacks a character data type, a single character is simply a one-length string. Square brackets can be used to access string elements.

Given a string, the task is to check whether the string is empty or not.

Example:

Input:

string=""

Output:

Given String is empty

Check if String is Empty

There are several ways to check whether the string is empty some of them are:

Method #1:Using len() function

The most general method for checking for zero-length strings is to use len(). Despite the fact that it ignores the fact that a string with only spaces should be considered an empty string even if it is not zero.

In Python, the len() function takes a sequence as an argument and returns the number of elements in that sequence. So, if we pass a string to the len() function as an argument, it returns the total number of characters in that string.

So, we can use the len() function to determine whether a string is empty or not by determining whether the number of characters in the string is zero or not.

Below is the implementation:

# given string
string = ""
# determining whether or not the given string is empty using len()
if len(string) == 0:
    print("Givem String is empty")
else:
    print("Given String is not empty")

Output:

Given String is empty

Method #2:Using not

The not operator can do the same thing as len() and search for 0 length strings, but it also considers strings with only spaces to be non-empty, which isn’t realistic.

In Python, an empty string is equivalent to False. So, to see if a string is empty or not, we can use the “not” operator, .

Below is the implementation:

# given string
string = ""
#  determining whether or not the given string is empty
if not string:
    print("Given String is empty")
else:
    print("Given String is not empty")

Output:

Given String is empty

Check whether string is empty/contain spaces

Using strip()

To get a copy of a string without leading and trailing white spaces, we can use the string’s strip() function. So, let’s use this to see if the string is empty or only contains white spaces.

Below is the implementation:

# given string
string = " "
#  determining whether or not the given string is empty
if string and string.strip():
print("Given String is not empty")
else:
print("Given String is empty")

Output:

Given String is empty

Using isspace()

The string class’s isspace() function returns True if the string only contains white spaces. So we can use this to see if a string is empty or only contains white spaces.

To get a copy of a string without leading and trailing white spaces, we can use the string’s strip() function. So, let’s use this to see if the string is empty or only contains white spaces.

Below is the implementation:

# given string
string = "      "
#  determining whether or not the given string is empty
if string and not string.isspace():
    print("Given String is not empty")
else:
    print("Given String is  empty")

Output:

Given String is empty

Related Programs:

Python Dictionary: Update() Function Tutorial and Examples

Python’s implementation of an associative array, which is a data structure, is dictionaries. A dictionary is a collection of key-value pairs. Each key-value pair represents a key and its associated value.

Enclosing a comma-separated list of key-value pairs in curly braces defines a dictionary. A colon ‘ : ‘ separates each key from its associated value.

In this post, we’ll look at how to use the update() method of the dict class in Python, as well as some examples of how to use it.

Tutorial and Examples for the update() function

The update() method in Python Dictionary updates the dictionary with elements from another dictionary object or an iterable of key/value pairs.

Syntax:

dictioanry_name.update(iterable)

Parameters:

 As parameters, this method accepts a dictionary or an iterable object of key/value pairs (typically tuples).

Return:

It does not return a value, but instead updates the Dictionary with elements from a dictionary object or an iterable object of key/value pairs.

If a key appears in the sequence argument but does not exist in the dictionary, it is added to the dictionary along with the given value. If the update() function is called without an argument, the dictionary is not modified.

Updating the value of a key in a Python dictionary

In the python dictionary, just build a temporary dictionary containing the new value key and move it to update() function for the update value.

Below is the implementation:

# Given Dictionary
dictionary = {'hello': 50, 'this': 100, 'is': 200, 'BTechGeeks': 300}
# updating the value of hello key to 400
dictionary.update({'hello': 400})
# printing the updated dictionary
print("Updated Dictionary : ", dictionary)

Output:

Updated Dictionary :  {'hello': 400, 'this': 100, 'is': 200, 'BTechGeeks': 300}

Using update function if key is not in dictionary

If the update() function is passed a key-value pair and the given key does not exist in the dictionary, it creates it with the given value.

Below is the implementation:

# Given Dictionary
dictionary = {'hello': 50, 'this': 100, 'is': 200, 'BTechGeeks': 300}
# updating the new key using update() function
dictionary.update({'python': 500})
# printing the updated dictionary
print("Updated Dictionary : ", dictionary)

Output:

Updated Dictionary :  {'hello': 50, 'this': 100, 'is': 200, 'BTechGeeks': 300, 'python': 500}

Updating Multiple keys in dictionary

If we want to change the values of multiple keys in the dictionary, we can use the update() function and pass them as key-value pairs. We can use a list of tuples or a temporary dictionary to bind multiple key-value pairs together.

Below is the implementation:

# Given Dictionary
dictionary = {'hello': 50, 'this': 100, 'is': 200, 'BTechGeeks': 300}
# updating the multiple keys using update() function
dictionary.update({'python': 500, 'this': 150, 'is': 250})
# printing the updated dictionary
print("Updated Dictionary : ", dictionary)

Output:

Updated Dictionary :  {'hello': 50, 'this': 150, 'is': 250, 'BTechGeeks': 300, 'python': 500}

Update/Modify the key name in python dictionary

A dictionary’s key cannot be modified. So, if we want to change the key name in the dictionary, we must remove the current key-value pair from the dictionary and replace it with a new key that has the same value.

Approach:

  • Using the pop function, remove the key and save the value of the current key in a variable.
  • Make a new key with the above value and a new name(key).

Below is the implementation of above approach:

# Given Dictionary
dictionary = {'hello': 50, 'this': 100, 'is': 200, 'BTechGeeks': 300}
# storing value of any key say hello in keyvalue variable after removing it
keyvalue = dictionary.pop('hello')
# updating the new key with the above value
dictionary.update({'Helloworld': keyvalue})
# printing the updated dictionary
print("Updated Dictionary : ", dictionary)

Output:

Updated Dictionary :  {'this': 100, 'is': 200, 'BTechGeeks': 300, 'Helloworld': 50}

 
Related Programs:

Python: Capitalize the First Letter of Each Word in a String?

A sequence of characters is referred to as a string.

Characters are not used by computers instead, numbers are used (binary). Characters appear on your computer, but they are internally stored and manipulated as a sequence of 0s and 1s.

In Python, a string is a set of Unicode characters. Unicode was designed to include every character in every language and to introduce encoding uniformity to the world. Python Unicode will tell you all about Unicode you need to know.

Example:

Input:

string = "this is btech geeks"

Output:

This Is Btech Geeks

Given a string, the task is to convert each word first letter to uppercase

Capitalize the First Letter of Each Word in a String

There are several ways to capitalize the first letter of each word in a string some of them are:

Method #1:Using capitalize() function

Syntax: given_string.capitalize()
Parameters: No parameters will be passed
Return : Each word’s first letter is capitalised in the string.

Approach:

  • Because spaces separate all of the words in a sentence.
  • We must use split to divide the sentence into spaces ().
  • We separated all of the words with spaces and saved them in a list.
  • Using the for loop, traverse the wordslist and use the capitalise feature to convert each word to its first letter capital.
  • Using the join function, convert the wordslist to a string.
  • Print the string.

Below is the implementation of above approach:

# given string
string = "this is btech geeks"
# convert the string to list and split it
wordslist = list(string.split())
# Traverse the words list and capitalize each word in list
for i in range(len(wordslist)):
  # capitizing the word
    wordslist[i] = wordslist[i].capitalize()
# converting string to list using join() function
finalstring = ' '.join(wordslist)
# printing the final string
print(finalstring)

Output:

This Is Btech Geeks

Method #2:Using title() function

Before returning a new string, the title() function in Python converts the first character in each word to Uppercase and the remaining characters in the string to Lowercase.

  • Syntax: string_name.title()
  • Parameters: string in which the first character of each word must be converted to uppercase
  • Return Value: Each word’s first letter is capitalised in the string.

Below is the implementation:

# given string
string = "this is btech geeks"
# using title() to convert all words first letter to capital
finalstring = string.title()
# print the final string
print(finalstring)

Output:

This Is Btech Geeks

Method #3:Using string.capwords() function

Using the spilt() method in Python, the string capwords() method capitalises all of the words in the string.

  • Syntax: string.capwords(given_string)
  • Parameters: The givenstring that needs formatting.
  • Return Value: Each word’s first letter is capitalised in the string.

Break the statement into words, capitalise each word with capitalise, and then join the capitalised words together with join. If the optional second argument sep is None or missing, whitespace characters are replaced with a single space and leading and trailing whitespace is removed.

Below is the implementation:

# importing string
import string
# given string
givenstring = "this is btech geeks"
# using string.capwords() to convert all words first letter to capital
finalstring = string.capwords(givenstring)
# print the final string
print(finalstring)

Output:

This Is Btech Geeks

Method #4:Using Regex

We’ll use regex to find the first character of each word and convert it to uppercase.

Below is the implementation:

# importing regex
import re

# function which converts every first letter of each word to capital

def convertFirstwordUpper(string):
    # Convert the group 2 to uppercase and join groups 1 and 2 together. 
    return string.group(1) + string.group(2).upper()


# given string
string = "this is btech geeks"

# using regex
resultstring = re.sub("(^|\s)(\S)", convertFirstwordUpper, string)
# print the final string
print(resultstring)

Output:

This Is Btech Geeks

Related Programs:

Python: How to Create an Empty Set and Append Items to It?

A Set is an unordered collection data type that can be iterated, mutated, and does not contain duplicate elements. Python’s set class represents the mathematical concept of a set. The main advantage of using a set over a list is that it has a highly optimised method for determining whether a specific element is contained in the set. This is based on the hash table data structure. Because sets are unordered, we cannot access items using indexes as we do in lists.

Characteristics of set:

  • Sets are not in any particular order.
  • Set elements are one of a kind. It is not permitted to use duplicate components.
  • A set’s elements can be modified, but the set’s elements must be of an immutable form.

In this article, we will first look at various ways to create an empty set, and then we will look at how to add or append items to the empty set.

Methods to Create an Empty Set

Method #1: Using set() to create an empty set in Python

A set is formed by enclosing all of the items (elements) within curly braces, separated by commas, or by using the built-in set() function.

It can contain an unlimited number of items of various types (integer, float, tuple, string etc.). A set, on the other hand, cannot have mutable elements such as lists, sets, or dictionaries as its elements.

It takes an optional iterable sequence and returns a set that has been initialised with the elements in the sequence. However, if no iterable sequence is passed to the function it returns an empty set.

Below is the implementation:

# creating new set
emptyset = set()
# printing the set
print(emptyset)
# printing the size of empty set
print("length of set = ", len(emptyset))

Output:

set()
length of set =  0

Method #2:Using empty set literal

Empty curly brackets, i.e., are commonly used in Python to create a dictionary. However, starting with Python 3.5, if we pass some comma separated arguments in curly square brackets, it will create a set with them. For example, 1, 2, 3 can be used to make a set with three values.

So, to make an empty set, we can use the same method.

Below is the implementation:

# creating new set
emptyset = {*()}
# printing the set
print(emptyset)
# printing the size of empty set
print("length of set = ", len(emptyset))

Output:

set()
length of set =  0

Append an item to an empty set

In set, insertion is accomplished via the set.add() function, which generates an appropriate record value for storage in the hash table. The same as searching for a specific item, i.e., O(1) on average. However, in the worst-case scenario, it can become O (n).

Below is the implementation:

# creating new set
emptyset = {*()}
# adding elements to set
emptyset.add('BTechGeeks')
emptyset.add('Hello')
emptyset.add('BTechGeeks')
# printing the set
print(emptyset)

Output:

{'BTechGeeks', 'Hello'}

Appending multiple items to the empty set

Using the set’s update() function, we can add multiple items to an empty set in a single line.

Below is the implementation:

# creating new set
emptyset = set()
# adding elements to set
emptyset.update(('Hello', 'BTechGeeks', 'Hello'))
# printing the set
print(emptyset)

Output:

{'Hello', 'BTechGeeks'}

Explanation:

The update() function takes a single or several iterable sequences as arguments and updates the set with all of the things in those sequences. In the preceding example, we created an empty set and then appended all of the items in a tuple to it in a single line.

 
Related Programs:

Check If Type of a Variable is String in Python

A string is a series of characters.

A character is nothing more than a representation of something. For example, there are 26 characters in the English language.

Computers do not work with characters, but rather with numbers (binary). Although characters are seen on your screen, they are stored and manipulated internally in a series of 0’s and 1’s.

A string in Python is a sequence of Unicode characters. Unicode was created in order to include every character in every language and to bring encoding uniformity.. Python Unicode can teach you everything you need to know about Unicode.

Examples:

Input:

string="hello"

Output:

Yes it is string variable

Determine whether a variable type is string

There are several ways to check whether a variable type is string some of them are:

Method #1 : Using type() function

The type() method returns the class type of the argument (object) that was passed as a parameter. The function type() is used mainly for debugging.

The type() function accepts two types of arguments: single and three argument. If only one argument is passed, type(obj), it returns the type of the given object. If type(name, bases, dict) is passed as an argument, it returns a new type object.

Syntax:

type(object)
type(name, bases, dict)

Parameters:

name : class name, which corresponds to the class’s __name__ attribute.
bases: a tuple of classes from which the current class is descended. Later corresponds to the attribute __bases__.
dict: a dictionary containing the class’s namespaces. Later is equivalent to the __dict__ attribute.

Return:

returns a new type class or, more precisely, a metaclass

We get the type of variable using type() and then compare it to str to see if it is a string variable.

Below is  the implementation:

# given variable
variable = "hello"
# comparing str and type of variable
if(type(variable) == str):
    print("Yes it is string variable")
else:
    print("No it is not string variable")

Output:

Yes it is string variable

Method #2 : Using isinstance() function

Python comprises a function for determining the type of a variable.

isinstance(object, classinfo)

The result of this function is If the given object is an instance of class classinfo or any of its subclasses, return True otherwise, return False.

Let’s see if we can use this to see if a variable is of the string form.

Below is the implementation:

# given variable
variable = "hello"
# using isinstance function to check whether the type of it is string or not
if(isinstance(variable, str)):
    print("Yes it is string variable")
else:
    print("No it is not string variable")

Output:

Yes it is string variable

Method #3 : By comparing types

We hard coded the string class in both previous solutions. But we can also compare the type of variable with the type of the empty string, without hard coding.

We know that the string object type is “”.

To compare the types we use this.

Below is the implementation:

# given variable
variable = "hello"
# comparing using type() function as type of string is ""
if(type(variable) == type("")):
    print("Yes it is string variable")
else:
    print("No it is not string variable")

Output:

Yes it is string variable

Related Programs:

Python: Iterate Over Dictionary (All Key-Value pairs)

Python’s implementation of an associative array, which is a data structure, is dictionaries. A dictionary is a collection of key-value pairs. Each key-value pair represents a key and its associated value.

Enclosing a comma-separated list of key-value pairs in curly braces defines a dictionary { }. A colon ‘ : ‘ separates each key from its associated value.

Note:

  • Keys are mapped to values in dictionaries, which are then stored in an array or series.
  • The keys must be of the hashable form, which means that their hash value must remain constant over their lifetime.

The keys and values of a dictionary are iterated over in the same order as they were generated in Python 3.6 and later. However, this behaviour varies between Python versions and is dependent on the dictionary’s insertion and deletion history.

Examples:

Input :

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

Output:

This 100
is 200
BTechGeeks 300

Traverse the dictionary

There are several ways to traverse the dictionary some of them are:

Method #1: Using for loop

To iterate over all keys in a dictionary, a dictionary object may also be used as an iterable object. As a result, we can apply for loop on a dictionary with ease. It loops through all the keys in the dictionary by using for in the dictionary. We will pick the value associated with each key and print it.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Using for loop to traverse the dictionary
for key in dictionary:
    # here key gives the key of the dictionary
    # Getting value at key
    value = dictionary[key]
    # printing values and keys
    print(key, value)

Output:

This 100
is 200
BTechGeeks 300

Method #2:Using items()

When dealing with dictionaries, you’ll almost certainly want to use both the keys and the values. .items(), a method that returns a new view of the dictionary’s items, is one of the most useful ways to iterate through a dictionary in Python.

This sequence is an iterable View object that contains all of the dictionary’s key,value elements. It is supported by the original dictionary. Let’s use this to iterate over all of the dictionary’s key-value pairs.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Using items and converting dictionary to list
dictlist = list(dictionary.items())
# Traverse the dictlist and print key and values of dictionary
for i in dictlist:
  # printing key and value
    print(i[0], i[1])

Output:

This 100
is 200
BTechGeeks 300

Method #3:Using List Comprehension

Since the items() function of a dictionary returns an iterable sequence of key-value pairs, we may use this list comprehension to iterate over all diction pairs.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Using list comprehension
[print(key, value) for key, value in dictionary.items()]

Output:

This 100
is 200
BTechGeeks 300

Filtering Items in dictionary

You can find yourself in a situation where you have an existing dictionary and want to construct a new one to store only the data that meets a set of criteria. This can be accomplished using an if statement inside a for loop, as shown below:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Create a new empty dictionary
newdictionary = dict()
# Traverse the original dictionary and check the condition
for key, value in dictionary.items():
    # If value meets the criteria, it should be saved in new dict.
    if value <= 200:
        newdictionary[key] = value
# printing the new dictionary
print(newdictionary)

Output:

{'This': 100, 'is': 200}

Related Programs:

Check If there are Duplicates in a List

Python Check If there are Duplicates in a List

Lists are similar to dynamically sized arrays (e.g., vector in C++ and ArrayList in Java) that are declared in other languages. Lists don’t always have to be homogeneous, which makes them a useful tool in Python. Integers, Strings, and Objects are all DataTypes that can be combined into a single list. Lists are mutable, meaning they can be modified after they’ve been formed.

Duplicates are integers, strings, or items in a list that are repeated more than once.

Given a list, the task is to check whether it has any duplicate element in it.

Examples:

Input:

givenlist=["hello", "this", "is", "BTechGeeks" , "hello"]

Output:

True

Explanation:

hello is repeated twice so the answer is Yes

Check whether list contains any repeated values

There are several ways to check duplicate elements some of them are:

Method #1 :Using list and count() function

The list class in Python has a method count() that returns the frequency count of a given list element.

list.count(Element)

It returns the number of times an element appears in the list.

Approach:

The idea is to iterate over all of the list’s elements and count the number of times each element appears.

If the count is greater than one, this element has duplicate entries.

Below is the implementation:

# function which return true if duplicates are present in list else false
def checkDuplicates(givenlist):
    # Traverse the list
    for element in givenlist:
        # checking the count/frequency of each element
        if(givenlist.count(element) > 1):
            return True
    # if the above loop do not return anuthing then there are no duplicates
    return False

#Driver code
# Given list
givenlist = ["hello", "this", "is", "BTechGeeks", "hello"]
# passing this list to checkDuplicates function
print(checkDuplicates(givenlist))

Output:

True

Time Complexity : O(n^2)

Method #2 : Using set()

Follow the steps below to see if a list contains any duplicate elements.

If the list does not contain any unhashable objects, such as list, use set().

When a list is passed to set(), the function returns set, which ignores duplicate values and keeps only unique values as elements..

Using the built-in function len(), calculate the number of elements in this set and the original list and compare them.

If the number of elements is the same, there are no duplicate elements in the original list ,if the number of elements is different, there are duplicate elements in the original list.

The following is the function that returns False if there are no duplicate elements and True if there are duplicate elements:

# function which return true if duplicates are present in list else false
def checkDuplicates(givenlist):
    # convert given list to set
    setlist = set(givenlist)
    # calculate length of set and list
    setlength = len(setlist)
    listlength = len(givenlist)
    # return the comparision between set length and list length
    return setlength != listlength


# Driver code
# Given list
givenlist = ["hello", "this", "is", "BTechGeeks", "hello"]
# passing this list to checkDuplicates function
print(checkDuplicates(givenlist))

Output:

True

Time Complexity : O(n(log(n))

Method #3: Using Counter() function from collections (Hashing)

Calculate the frequencies of all elements using Counter() function which will be stored as frequency dictionary.

If the length of frequency dictionary is equal to length of list then it has no duplicates.

Below is the implementation:

# importing Counter function from collections
from collections import Counter

# function which return true if duplicates are present in list else false


def checkDuplicates(givenlist):
    # Calculating frequency using counter() function
    frequency = Counter(givenlist)
    # compare these two lengths and return it
    return len(frequency) != len(givenlist)


# Driver code
# Given list
givenlist = ["hello", "this", "is", "BTechGeeks", "hello"]
# passing this list to checkDuplicates function
print(checkDuplicates(givenlist))

Output:

True

Time Complexity : O(n)
Related Programs:

Related Programs: