Five Python Tricks to make your work easy

Five Python Tricks to make your work easy

Python is one of the world's most popular programming languages. You can use Python for Data Science, Machine Learning, Web Development, Desktop Application. Python is very easy to learn and use. So, here are 5 cool python tricks to make everyday works easy.

What is in this article

  • Merging two dicts in Python 3.5+ with a single expression
  • How to sort a Python dict by value
  • Different ways to test multiple flags at once in Python
  • Python's built-in HTTP server
  • Check if all elements in a list are equal

Merging two dicts in Python 3.5+ with a single expression

# How to merge two dictionaries in Python 3.5+
>>> x = {'p': 1, 'q': 2}
>>> y = {'q': 3, 'r': 4}

>>> z = {**x, **y}

>>> z
{'p': 1, 'q': 3, 'r': 4}

# In Python 2.x you could
# use this:
>>> z = dict(x, **y)
>>> z
{'p': 1, 'q': 3, 'r': 4}

# In these examples, Python merges dictionary keys
# in the order listed in the expression, overwriting 
# duplicates from left to right.

How to sort a Python dict by value

# How to sort a Python dict by value

>>> test = {'a': 4, 'b': 3, 'c': 2, 'd': 1}

>>> sorted(test.items(), key=lambda x: x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

# Or:

>>> import operator
>>> sorted(test.items(), key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

Different ways to test multiple flags at once in Python

# Different ways to test multiple
# flags at once in Python
x, y, z = 0, 1, 0

if x == 1 or y == 1 or z == 1:
    print('passed')

if 1 in (x, y, z):
    print('passed')

# These only test for truthiness:
if x or y or z:
    print('passed')

if any((x, y, z)):
    print('passed')

Python's built-in HTTP server

# Python has an HTTP server built into the
# standard library. This is super handy for
# previewing websites.

# Python 3.x
$ python3 -m http.server

# Python 2.x
$ python -m SimpleHTTPServer 8000

# (This will serve the current directory at
#  http://localhost:8000)

Check if all elements in a list are equal

# Pythonic ways of checking if all
# items in a list are equal:

>>> lst = ['a', 'a', 'a']

>>> len(set(lst)) == 1
True

>>> all(x == lst[0] for x in lst)
True

>>> lst.count(lst[0]) == len(lst)
True

# I ordered those from "most Pythonic" to "least Pythonic" 
# and  "least efficient" to "most efficient". 
# The len(set()) solution is idiomatic,  but constructing 
# a set is less efficient memory and speed-wise.

If you liked this content make sure to share this with your code mates. Thanks for reading.