Dictionary in Python provides various built-in methods using which we can perform various operations on the dictionary object and its elements. These methods help us to manipulate and interact with dictionary objects.
In previous articles, we explored various scenario to interact and manipulate the dictionary elements. We explored to add, update and remove elements from dictionary. In this article, we will learn about other built-in methods provided with dictionary in Python.
Built-in methods
In this article, we will explore following built-in methods:
all()
any()
len()
sorted()
all()
method
all()
is a general built-in method in Python and it can be used with various iterable datatypes like list, tuple, set and dictionary.
- In case of dictionary
all()
method checks whether all the keys (or values) in the dictionary are consideredTrue
orFalse
. - Syntax =>
result = all(dictionary)
- On the dictionary,
all()
method applies on the dictionary’s keys by default. It returnsTrue
if all keys areTrue
and returnsFalse
if any of the key isFalse
. - If
all()
method to apply on dictionary values =>result = all(dictionary.values())
all()
method appliesAND
condition on all the keys or values of dictionary.
# dictionary built-in function - all()
print("dictionary built-in function - all()")
courses = {"c1": "Python", "c2": "AWS", "c3": "Azure", "c4": "Java"}
print(courses)
print(all(courses)) # all() method, default apply on keys
print(all(courses.values())) # all() method, apply on values
numbers_dict = {0: "Python", 1: "AWS", 2: "Azure", 3: "Java"}
print(numbers_dict)
print(all(numbers_dict)) # all() method, default apply on keys
print(all(numbers_dict.values())) # all() method, apply on values
- In the first scenario, we are defining a dictionary referenced by variable
courses
. This dictionary all keys and values are present and neither of any key or value isFalse
. Bothall(courses)
andall(courses.values())
will returnTrue
. - In the second scenario, defined dictionary is referenced by variable
numbers_dict
. All keys of this dictionary are numeric. One of the key is0
, boolean of which will returnFalse
and one of the value isNone
, boolean of which also returnFalse
. Bothall(numbers_dict)
andall(numbers_dict.values())
will returnFalse
.
Program Output
dictionary built-in function - all()
{'c1': 'Python', 'c2': 'AWS', 'c3': 'Azure', 'c4': 'Java'}
True # all(courses) return True
True # all(courses.values()) return True
{0: 'Python', 1: 'AWS', 2: 'Azure', 3: None}
False # all(numbers_dict) return True
False # all(numbers_dict.values()) return True
From the output, Both all(courses)
and all(courses.values())
return True
and Both all(numbers_dict)
and all(numbers_dict.values())
return False
.
any()
method
Similar to all()
method, any()
is a general built-in method in Python and it can be used with various iterable datatypes like list, tuple, set and dictionary.
- In case of dictionary
any()
method checks whether any one of the key (or value) in the dictionary isTrue
or not. - Syntax =>
result = any(dictionary)
- On the dictionary,
any()
method applies on the dictionary’s keys by default. It returnsTrue
if any one of the keys areTrue
and returnsFalse
if all of the keys isFalse
. - If
any()
method to apply on dictionary values =>result = any(dictionary.values())
any()
method appliesOR
condition on all the keys or values of dictionary.
# dictionary built-in function - any()
print("dictionary built-in function - any()")
numbers_dict = {0: "Python", 1: "AWS", 2: "Azure", 3: None}
print(numbers_dict)
print(any(numbers_dict)) # any() method, default apply on keys
print(any(numbers_dict.values())) # any() method, apply on values
numbers_dict = {0: None, 0: None, 0: None} # dictionary does allow duplicate keys
print(numbers_dict)
print(any(numbers_dict)) # any() method, default apply on keys
print(any(numbers_dict.values())) # any() method, apply on values
- In the first scenario, we are defining a dictionary referenced by variable
numbers_dict
. All keys of this dictionary are numeric. Except key0
, boolean of all other keys will returnTrue
. In case of values except valueNone
, boolean of also other values will returnTrue
. Bothany(numbers_dict)
andany(numbers_dict.values())
will returnTrue
. - In the second scenario, defined dictionary is referenced by variable
numbers_dict
. All keys of this dictionary are0
, boolean of which will returnFalse
and all values of this dictionary areNone
, boolean of which also returnFalse
. Since all keys and values will returnFalse
, so bothany(numbers_dict)
andany(numbers_dict.values())
will returnFalse
.
Program Output
dictionary built-in function - any()
{0: 'Python', 1: 'AWS', 2: 'Azure', 3: None}
True # all(numbers_dict) return True
True # all(numbers_dict.values()) return True
{0: None}
False # all(numbers_dict) return False
False # all(numbers_dict.values()) return False
From the output, Both all(courses)
and all(courses.values())
return True
and Both all(numbers_dict)
and all(numbers_dict.values())
return False
.
len()
method
len()
is also a built-in method in Python and it can be used with various iterable datatypes like string, list, tuple, set and dictionary. len()
method returns the number of key-value pairs in the dictionary. Syntax of len() method => return = len(dictionary)
# dictionary built-in function - len()
print("dictionary built-in function - len()")
courses = {"c1": "Python", "c2": "AWS", "c3": "Azure", "c4": "Java"} # 4 key-value pairs
print(courses) # print element of dictionary
print(len(courses)) # print length of dictionary
empty_dict = {}
length = len(empty_dict)
print(length)
We have defined a dictionary referenced by variable courses
. This dictionary has 4 key-value pairs. len(courses)
will return 4. For empty dictionary len(empty_dict)
will return 0.
Program Output
dictionary built-in function - len()
{'c1': 'Python', 'c2': 'AWS', 'c3': 'Azure', 'c4': 'Java'}
4 # key-value pairs in courses
0 # key-value pairs in empty_dict
sorted()
method
sorted()
is also a built-in method in Python and it can also be used with various iterable datatypes like string, list, tuple, set and dictionary. sorted()
method allows to sort the dictionary by keys, values, or custom criteria. Syntax of sorted()
method:
sorted_keys = sorted(dictionary, key, reverse)
dictionary
(mandatory) – It is the dictionary key-value pairs on which sorting happens.key
(optional) – If this argument is not given, then by default sorting will happen on the dictionary keys. But if we need sorting on values or custom elements, then we can pass this argument.reverse
(optional) – This is an optional parameter. By default its value if False. If passed asTrue
, then sorting happens in Descending order. By default,sorted()
method sorts in Ascending order.sorted_keys
-It returns a new sorted list of the dictionary’s keys, values, or key-value pairs.
sorted()
Dictionary Keys
# dictionary built-in function - sorted()
print("dictionary built-in function - sorted()")
courses = {"c3": "Python", "c2": "AWS", "c4": "Azure", "c1": "Java"}
print(courses) # unsorted key-value pair
print(sorted(courses)) # sorting on keys in ascending order
print(sorted(courses, reverse=True)) # sorting on keys in descending order
Unsorted keys dictionary referenced by courses
. Method sorted(courses)
will sort the courses
dictionary keys in ascending order. sorted(courses, reverse=True)
will sort the courses
dictionary keys in descending order.
Program Output
dictionary built-in function - sorted()
{'c3': 'Python', 'c2': 'AWS', 'c4': 'Azure', 'c1': 'Java'}
['c1', 'c2', 'c3', 'c4'] # sorted keys in ascending order
['c4', 'c3', 'c2', 'c1'] # sorted keys in descending order
From the output, ['c1', 'c2', 'c3', 'c4']
sorted keys in ascending order and ['c4', 'c3', 'c2', 'c1']
sorted keys in descending order.
sorted()
Dictionary Values
# dictionary built-in function - sorted()
print("dictionary built-in function - sorted()")
courses = {"c3": "Python", "c2": "AWS", "c4": "Azure", "c1": "Java"}
print(courses) # unsorted key-value pair
print(sorted(courses.items(), key=lambda item: item[1])) # sorting on values in ascending order
print(sorted(courses.items(), key=lambda item: item[1], reverse=True)) # sorting on values in descending order
- Method
sorted(courses.items(), key=lambda item: item[1])
will sort thecourses
dictionary by values in ascending order.key
is given value ofitem[1]
. sorted(courses.items(), key=lambda item: item[1], reverse=True)
will sort thecourses
dictionary by values in descending order.key
is given value ofitem[1]
.
Program Output
dictionary built-in function - sorted()
{'c3': 'Python', 'c2': 'AWS', 'c4': 'Azure', 'c1': 'Java'}
[('c2', 'AWS'), ('c4', 'Azure'), ('c1', 'Java'), ('c3', 'Python')] # sorted by values in ascending order
[('c3', 'Python'), ('c1', 'Java'), ('c4', 'Azure'), ('c2', 'AWS')] # sorted by values in descending order
[('c2', 'AWS'), ('c4', 'Azure'), ('c1', 'Java'), ('c3', 'Python')]
sorted key-value pair in ascending order.[('c3', 'Python'), ('c1', 'Java'), ('c4', 'Azure'), ('c2', 'AWS')]
sorted key-value pair in descending order.
Summary
In this article, we learn about built-in methods in Python and their usage with dictionary object. We explored following scenarios:
Code – Github Repository
All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.