Understand Python Dictionary Comprehensions: A Beginner Guide
Python Tutorial
Understand Python Dictionary Comprehensions: A Beginner Guide

A dictionary comprehension is similar to a list comprehension except that it produces a dictionary object instead of

a list.

A basic example:

Python 2.x Version ≥ 2.7

{x: x * x for x in (1, 2, 3, 4)}

# Out: {1: 1, 2: 4, 3: 9, 4: 16}

which is just another way of writing:

dict((x, x * x) for x in (1, 2, 3, 4))

# Out: {1: 1, 2: 4, 3: 9, 4: 16}

As with a list comprehension, we can use a conditional statement inside the dict comprehension to produce only

the dict elements meeting some criterion.

Python 2.x Version ≥ 2.7

{name: len(name) for name in ('Stack', 'Overflow', 'Exchange') if len(name) > 6}

# Out: {'Exchange': 8, 'Overflow': 8}

Or, rewritten using a generator expression.

dict((name, len(name)) for name in ('Stack', 'Overflow', 'Exchange') if len(name) > 6)

# Out: {'Exchange': 8, 'Overflow': 8}

Starting with a dictionary and using dictionary comprehension as a key-value pair filter

Python 2.x Version ≥ 2.7

initial_dict = {'x': 1, 'y': 2}

{key: value for key, value in initial_dict.items() if key == 'x'}

# Out: {'x': 1}

Switching key and value of dictionary (invert dictionary)

If you have a dict containing simple hashable values (duplicate values may have unexpected results):

my_dict = {1: 'a', 2: 'b', 3: 'c'}

and you wanted to swap the keys and values you can take several approaches depending on your coding style:

swapped = {v: k for k, v in my_dict.items()}

swapped = dict((v, k) for k, v in my_dict.iteritems())

swapped = dict(zip(my_dict.values(), my_dict))

swapped = dict(zip(my_dict.values(), my_dict.keys()))

swapped = dict(map(reversed, my_dict.items()))

print(swapped)

# Out: {a: 1, b: 2, c: 3}

Python 2.x Version ≥ 2.3

If your dictionary is large, consider importing itertools and utilize izip or imap.

Merging Dictionaries

Combine dictionaries and optionally override old values with a nested dictionary comprehension.

dict1 = {'w': 1, 'x': 1}

dict2 = {'x': 2, 'y': 2, 'z': 2}

{k: v for d in [dict1, dict2] for k, v in d.items()}

# Out: {'w': 1, 'x': 2, 'y': 2, 'z': 2}

However, dictionary unpacking (PEP 448) may be a preferred.

Python 3.x Version ≥ 3.5

{**dict1, **dict2}

# Out: {'w': 1, 'x': 2, 'y': 2, 'z': 2}

Note: dictionary comprehensions were added in Python 3.0 and backported to 2.7+, unlike list comprehensions,

which were added in 2.0. Versions < 2.7 can use generator expressions and the dict() builtin to simulate the

behavior of dictionary comprehensions.

Related

Understanding Python Argparse Library: Parse Command-line Options

argument parsing It should be taken into account that we should not handle sys.argv directly, mainly when our programs take complex parameters or multiple filenames. Alternatively, we should use Python's argparse library, which handles command- line arguments in a systematic way, making it accessible to write user-friendly command-line programs. In other words, Python has a module called argparse (htt ps://docs.python.org/3/library/argparse.html) in the standard library for parsing command-line arguments. First, the program determines what arguments it requires. Then, argparse will work out how to parse these arguments to sys.argv. Also, argparse produces help and usage messages, and issues errors when invalid arguments are provided. The minimum example to introduce this module is given here, argparse_minimal.py, which is shown as follows: # Import the required packages import argparse # We first create the ArgumentParser object # The created object 'parser' will have the necessary information # to parse the command-line arguments into data types. parser = argparse.ArgumentParser() # The information about program arguments is stored in 'parser' and used when parse_args() is called. # ArgumentParser parses arguments through the parse_args() method: parser.parse_args() Running this script with no parameters results in nothing being displayed to stdout. However, if we include the --help (or -h) option, we will get the usage message of the script: usage: argparse_minimal.py [-h] optional arguments: -h, --help show this help message and exit Specifying any other parameters results in an error, for example: argparse_minimal.py 6 usage: argparse_minimal.py [-h] argparse_minimal.py: error: unrecognized arguments: 6 message information will be shown. No other possibilities are allowed as no arguments are defined. In this way, the second example to introduce argparse is to add a parameter, which can be seen in the argparse_positional_arguments.py example: # Import the required packages import argparse # We first create the ArgumentParser object # The created object 'parser' will have the necessary information # to parse the command-line arguments into data types. parser = argparse.ArgumentParser() # We add a positional argument using add_argument() including a help parser.add_argument("first_argument", help="this is the string text in connection with first_argument") # The information about program arguments is stored in 'parser' # Then, it is used when the parser calls parse_args(). # ArgumentParser parses arguments through the parse_args() method: args = parser.parse_args() # We get and print the first argument of this script: print(args.first_argument) We added the add_argument() method. This method is used to specify what command-line options the program will accept. In this case, the first_argument argument is required. Additionally, the argparse module stores all the parameters, matching its name with the name of each added parameter— in this case, first_argument. Therefore, to obtain our parameter, we perform args.first_argument. […]