Skip to content

Instantly share code, notes, and snippets.

@dungdt88
Last active January 22, 2020 13:34
Show Gist options
  • Save dungdt88/c92a6f4742bd55944c70e922de6ffc45 to your computer and use it in GitHub Desktop.
Save dungdt88/c92a6f4742bd55944c70e922de6ffc45 to your computer and use it in GitHub Desktop.

Source: https://www.toptal.com/python/tips-and-practices

This resource contains a collection of Python best practices and Python tips provided by our Toptal network members. As such, this page will be updated on a regular basis to include additional information and cover emerging Python techniques. This is a community driven project, so you are encouraged to contribute as well, and we are counting on your feedback.

Python is a high level language used in many development areas, like web development (Django, Flask), data analysis (SciPy, scikit-learn), desktop UI (wxWidgets, PyQt) and system administration (Ansible, OpenStack). The main advantage of Python is development speed. Python comes with rich standard library, a lot of 3rd party libraries and clean syntax. All this allows a developer to focus on the problem they want to solve, and not on the language details or reinventing the wheel.

Check out the Toptal resource pages for additional information on Python. There is a Python hiring guide, Python job description, common Python mistakes, and Python interview questions.

Learn to Use Python Dictionary Dictionary data structure in Python is a way to store data; moreover, it is powerful and easy to use. Dictionaries are found in other languages as “associative memories” or “associative arrays”. In Python, a dictionary is an unordered set of key: value pairs, with the requirement that each key is unique.

How should we use a dictionary in everyday development?

Let’s examine some common use cases with accompanying code examples. Let’s say you use many if/else clauses in your code:

if name == "John": 
   print "This is John, he is an artist"
elif name == "Ted":
   print "This is Ted, he is an engineer"
elif name == "Kennedy":
   print "This is Kennedy, he is a teacher"

By using a dictionary, we can write the same code like this:

name_job_dict = {
   "Josh": "This is John, he is an artist",
   "Ted": "This is Ted, he is an engineer",   
   "Kenedy": "This is Kennedy, he is a teacher",
}
print name_job_dict[name]

The second use case is when we need a default value for a key:

def count_duplicates(numbers):
   result = {}
   for number in numbers:
       if number not in result:  # No need for if here
           result[key] = 0
       result[number] += 1
   return result

By using setdefault, we get cleaner code:

def count_duplicates(numbers):
   result = {}
   for number in numbers:
       result.setdefault(number, 0)  # this is clearer
       result[number] += 1
   return result

We can also use the dictionary to manipulate lists:

>>> characters = {'a': 1, 'b': 2}
>>> characters.items() // return a copy of a dictionary’s list of (key, value) pairs (https://docs.python.org/2/library/stdtypes.html#dict.items)
[('a', 1), ('b', 2)]
>>> characters = [['a', 1], ['b', 2], ['c', 3]]
>>> dict(characters) // return a new dictionary initialized from a list (https://docs.python.org/2/library/stdtypes.html#dict)
{'a': 1, 'b': 2, 'c': 3}

If necessary, it is easy to change a dictionary form by switching the keys and values – changing {key: value} to a new dictionary {value: key} – also known as inverting the dictionary:

>>> characters = {'a': 1, 'b': 2, 'c': 3}
>>> invert_characters = {v: k for k, v in characters.iteritems()}
>>> invert_characters
{1: 'a', 2: 'b', 3: 'c'}

The final tip is related to exceptions. Developers should watch out for exceptions. One of the most annoying is the KeyError exception. To handle this, developers must first check whether or not a key exists in the dictionary.

>>> character_occurrences = {'a': [], ‘b’: []}
>>> character_occurrences[‘c’]
KeyError: 'c'
>>> if ‘c’ not in character_occurrences:
        character_occurrences[‘c’] = []
>>> character_occurrences[‘c’]
[]
>>> try:
        print character_occurrences[‘d’]
    except: 
        print “There is no character `d` in the string”

However, to achieve clean and easily testable code, avoiding exceptions catch and conditions is a must. So, this is cleaner and easier to understand if the defaultdict, in collections, is used.

>>> from collections import defaultdict
>>> character_occurrences = defaultdict(list)
>>> character_occurrences['a']
[]
>>> character_occurrences[‘b’].append(10)
>>> character_occurrences[‘b’].append(11)
>>> character_occurrences[‘b’]
[10, 11]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment