Build Dictionary in Python Loop – List and Dictionary Comprehensions

The short form is as follows (called dict comprehension, as analogy to the list comprehension, set comprehension etc.): x = { row.SITE_NAME : row.LOOKUP_TABLE for row in cursor } so in general given some _container with some kind of elements and a function _value which for a given element returns the value that you want …

Read more

Nested dictionary comprehension python

{inner_k: myfunc(inner_v)} isn’t a dictionary comprehension. It’s just a dictionary. You’re probably looking for something like this instead: data = {outer_k: {inner_k: myfunc(inner_v) for inner_k, inner_v in outer_v.items()} for outer_k, outer_v in outer_dict.items()} For the sake of readability, don’t nest dictionary comprehensions and list comprehensions too much.

Selecting elements of a Python dictionary greater than a certain value

.items() will return (key, value) pairs that you can use to reconstruct a filtered dict using a list comprehension that is feed into the dict() constructor, that will accept an iterable of (key, value) tuples aka. our list comprehension: >>> d = dict(a=1, b=10, c=30, d=2) >>> d {‘a’: 1, ‘c’: 30, ‘b’: 10, ‘d’: …

Read more

Why is this loop faster than a dictionary comprehension for creating a dictionary?

You are testing with way too small an input; while a dictionary comprehension doesn’t have as much of a performance advantage against a for loop when compared to a list comprehension, for realistic problem sizes it can and does beat for loops, especially when targeting a global name. Your input consists of just 3 key-value …

Read more

How can I use if/else in a dictionary comprehension?

You’ve already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon: { (some_key if condition else default_key):(something_if_true if condition else something_if_false) for key, value …

Read more

Create a dictionary with comprehension

Use a dict comprehension (Python 2.7 and later): {key: value for (key, value) in iterable} Alternatively for simpler cases or earlier version of Python, use the dict constructor, e.g.: pairs = [(‘a’, 1), (‘b’, 2)] dict(pairs) #=> {‘a’: 1, ‘b’: 2} dict([(k, v+1) for k, v in pairs]) #=> {‘a’: 2, ‘b’: 3} Given separate …

Read more