Built-in methods – Python

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 considered True or False.
  • Syntax => result = all(dictionary)
  • On the dictionary, all() method applies on the dictionary’s keys by default. It returns True if all keys are True and returns False if any of the key is False.
  • If all() method to apply on dictionary values => result = all(dictionary.values())
  • all() method applies AND 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 is False. Both all(courses) and all(courses.values()) will return True.
  • In the second scenario, defined dictionary is referenced by variable numbers_dict. All keys of this dictionary are numeric. One of the key is 0, boolean of which will return False and one of the value is None, boolean of which also return False. Both all(numbers_dict) and all(numbers_dict.values()) will return False.

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 is True or not.
  • Syntax => result = any(dictionary)
  • On the dictionary, any() method applies on the dictionary’s keys by default. It returns True if any one of the keys are True and returns False if all of the keys is False.
  • If any() method to apply on dictionary values => result = any(dictionary.values())
  • any() method applies OR 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 key 0, boolean of all other keys will return True. In case of values except value None, boolean of also other values will return True. Both any(numbers_dict) and any(numbers_dict.values()) will return True.
  • In the second scenario, defined dictionary is referenced by variable numbers_dict. All keys of this dictionary are 0, boolean of which will return False and all values of this dictionary are None, boolean of which also return False. Since all keys and values will return False, so both any(numbers_dict) and any(numbers_dict.values()) will return False.

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 as True, 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 the courses dictionary by values in ascending order. key is given value of item[1].
  • sorted(courses.items(), key=lambda item: item[1], reverse=True) will sort the courses dictionary by values in descending order. key is given value of item[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.

Python Topics


Interview Questions & Answers

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *