Monthly Archives: December 2017

How to sort a dictionary by values in Python

Tweet By definition, dictionary are not sorted (to speed up access). Let us consider the following dictionary, which stores the age of several persons:

If you want to sort this dictionary by values (i.e., the age), you must be … Continue reading

Posted in Python, Uncategorized | Tagged , | Leave a comment

Python: how to copy a list

Tweet To explain how to create a copy of a list, let us first create a list. We will use a simple list of 4 items:

Why do we want to create a copy anyway ? Well, because in … Continue reading

Posted in Python | Tagged , | Leave a comment

Python: ternary operator

Tweet In C language (and many other languages), there is a compact ternary conditional operator that is a compact if-else conditional construct. For instance, in C, a traditional if-else construct looks like:

and the equivalent ternary operator looks like: … Continue reading

Posted in Python | Leave a comment

Difference between __repr__ and __str__ in Python

Tweet When implementing a class in Python, you usually implement the __repr__ and __str__ methods. __str__ should print a readable message __repr__ should print a message that is unambigous (e.g. name of an identifier, class name, etc). You can see … Continue reading

Posted in Python | Tagged , | 2 Comments

python: how to merge two dictionaries

Tweet Let us suppose two dictionaries storing ages of different individuals:

If you do mind losing the contents of either list1 or list2 variable, you can update one of the other as follows:

Now list1 variable contains:

Continue reading

Posted in Python | Tagged | Leave a comment

Search for a pattern in a set of files using find and grep commands

Tweet A common task for developers is to search for a pattern amongst a bunch of files that are in different directories. For instance, you are looking for the pattern “import sys” within a set of Python files. Those files … Continue reading

Posted in Linux | Tagged , | Leave a comment