8 Extremely Useful Python One-liners for your Next Project

These Python code snippets can save you a bunch of time on your next project so make sure to read along!

Kush
ITNEXT

--

A photo of some Python code by Chris Ried on Unsplash
Photo by Chris Ried on Unsplash

Sometimes when writing code you find yourself needing to do something trivial but you’re just not sure how to do it, and when you eventually find a solution it might not be the most efficient or prettiest thing you could’ve came up with. That’s why today I’ve compiled a list of very useful Python one-liners which can help you with those trivial tasks. There is no need to install any third-party libraries for any of these snippets as they all use built-in modules.

Here’s a list of the topics we will cover today:

  1. Ordering a dictionary based on its values
  2. Printing any data in an easy-to-read format
  3. Printing the value of variables using f-strings
  4. Generating random hex strings
  5. Returning a list of all the permutations of an iterable
  6. Measuring the exact execution time for a computation
  7. Reading and extracting JSON data from a file to a dictionary
  8. Getting the current data and time in string format

Now, let’s get started.

Ordering a dictionary based on its values:

Often you might come across a scenario where you have a dictionary, and you need to order it based on the values of the dictionary. For example, this could be a dictionary containing players and their high scores and you want to get the top 10 players based on their scores.

This can easily be done by creating a new dictionary and iterating through a sorted list of the values in our original dictionary, then we can add the key value pairs to our new dictionary. This can be done all in one line using dictionary comprehension:

Output:

{'a': 1, 'd': 5, 'b': 6, 'c': 7, 'e': 9}

Printing any data in an easy-to-read format:

Do you sometimes have a lot of data, or data which varies in type, and you want to print it all out to the terminal for further inspection but it all prints in one huge line and you can’t see anything? Well for that you can use the built-in pprint module in Python, this will automatically format your data and print it nicely to your terminal. Here I have a dictionary with random values and use the pprint function from the pprint module to print it out:

Output:

{'ahead': {'between': 'boy',
'blew': 'allow',
'fly': 'throat',
'inside': False,
'path': 1972198692,
'toward': -1359495784.298975}}

Printing the value of variables using f-strings:

When debugging it is very useful to print out a variables value, but if you have a bunch of variables and their values to print out, how do you know which variable is equal to what value? For this we can use f-strings in python to print out the value of the variable and the name of the variable itself. All we need to do is append an equals sign ‘=’ to the end of a variable name in an f-string as such:

Output:

x=5
y='hello world!'

Generating random hex strings:

Random strings can be useful in a variety of situations, you may need them to create a secure password or to make a random username. We can do this very easily in python with the built-in secrets module and supplying the number of bytes to be used in our hex string:

Output:

2957eeade5b13b6d

You can learn more about the secrets module here.

Returning a list of all the permutations of an iterable:

If you had an iterable, such as a string or list, and you wanted to know how many permutations could be created from that iterable, you can use the built-in permutations function from the itertools module in Python. When you call the permutations function and convert the object into a list, a list of tuples is returned with each value being a letter. We can iterate through these tuples and join all the letters into one string and append it to one list as such:

Output:

['abcd', 'abdc', 'acbd', 'acdb', 'adbc', 'adcb', 'bacd', 'badc', 'bcad', 'bcda', 'bdac', 'bdca', 'cabd', 'cadb', 'cbad', 'cbda', 'cdab', 'cdba', 'dabc', 'dacb', 'dbac', 'dbca', 'dcab', 'dcba']

Measuring the exact execution time for a computation:

Measuring the time for an algorithm to compute some data is extremely important as you can see the pitfalls of your algorithm and estimate how long it could to process larger data. We can use the perf_counter function from the time module to print out the number of seconds it took your computer to run some code. We first need to create an object which holds the starting time, and then when our computation is finished, we can subtract the starting time from the current time and print the result:

Output:

0001505000000000048

Yes, I know this isn’t strictly a one-liner but it’s still incredibly useful!

Reading and extracting JSON data from a file to a dictionary:

JSON is extremely useful when it comes to storing any type of data as it can easily be sent around the internet and stored in a file. When working with JSON data in Python, we must firstly import the built-in json library. We can then use the loads function and pass in a string which contains all our unparsed JSON data. Here we can read the data from a file and use the loads function to convert it into a Python dictionary:

Output:

{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}

Getting the current date and time in string format:

You may find yourself in the need to get the current date or time in string format, this could be for accessing an API where in the request you need to submit some datetime information. We can use the datetime module to fetch the current time and then use the strftime method to format the time into a string using special formatting characters:

Output:

25-04-21 15:21:08

Final thoughts:

In almost every one of my projects I use a handful of these one-liners and they’ve proved to be very handy to remember. I hope you learned something new today and make sure to save this post somewhere for future reference as well.

Thank you for reading! 💖

--

--

Writer for

20 year old self-taught Python dev | Been programming for 7 years | Love making weekend projects | U.K.