How to Find the Maximum Value in a Python Dict?

There are three problem variants of finding the maximum value in a Python dictionary: Find the maximum value and return this maximum value Find the maximum value and return a (key, value) tuple of both the key and the max value itself Find the maximum value and return only the key assigned to the max … Read more

How to Sort a Dictionary in Python By Key?

To sort a dictionary by key in Python, use the dictionary comprehension expression {key:dict[key] for key in sorted(dict)} to create a new dictionary with keys in sorted order. You iterate over all keys in sorted order, obtain their associated values with rank[key], and put them into a new dictionary. Python dictionaries preserve the order—even if … Read more

Python Boolean Variables

Python Boolean variables are set to either the True or False keywords. Both keywords require an Upper Case letter—lowercase letters are interpreted as normal variable or function names, so you could set true = True. A variable is of type Boolean if type(variable) results in the output <class ‘bool’>. You can convert any object to … Read more

Python’s __import__() Function — Dynamically Importing a Library By Name

Python’s built-in “dunder” function __import__() allows you to import a library by name. For example, you may want to import a library that was provided as a user input, so you may only have the string name of the library. For example, to import the NumPy library dynamically, you could run __import__(‘numpy’). In this tutorial, … Read more

How to Sort in Python with the Lambda Function as Key Argument?

Challenge: This article shows how to sort a Python list using the key argument that takes a function object as an argument. Quick Solution: You can use the lambda function to create the function on the fly as shown in the following example: Explanation: The code uses the key argument and passes a lambda function … Read more

The Pathfinder Graph Algorithm in Python

Knowing the basics is what sets apart the great from the intermediate coders. In other words, a simple and effective way to grow your skills is to learn the basics of computer science. Python Pathfinder Algorithm In this tutorial, you’ll learn about the pathfinder algorithm that recursively determines whether there’s a direct or indirect path … Read more

Dictionaries and Unpacking Arguments in Python

Programming is about using lower-level functionality to create higher-level functionality. In general, any programming language is a collection of functions that in turn build upon functions provided by the operating system. You must master the art of building your own code with the help of existing functionality, instead of reinventing the wheel! Keyword Arguments Functions … Read more