Questions tagged [dictionary-comprehension]

A syntactic construct in Python which provides a concise way to create dictionaries.

Dictionary comprehensions can be used to construct dictionaries in one line. For simple tasks, a dictionary comprehension may be more readable than dictionaries built using looping constructs.

Dictionary comprehensions tend to consist of an input sequence of either a list or another dictionary, variable bindings, a filtering predicate, and an output expression.

The result is a new dictionary.

Dictionary comprehensions are very similar to list comprehensions.

857 questions
1554
votes
17 answers

Create a dictionary with comprehension

Can I use list comprehension syntax to create a dictionary? For example, by iterating over pairs of keys and values: d = {... for k, v in zip(keys, values)}
flybywire
  • 261,858
  • 191
  • 397
  • 503
512
votes
13 answers

Why is there no tuple comprehension in Python?

As we all know, there's list comprehension, like [i for i in [1, 2, 3, 4]] and there is dictionary comprehension, like {i:j for i, j in {1: 'a', 2: 'b'}.items()} but (i for i in (1, 2, 3)) will end up in a generator, not a tuple comprehension.…
243
votes
5 answers

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

Does there exist a way in Python 2.7+ to make something like the following? { something_if_true if condition else something_if_false for key, value in dict_.items() } I know you can make anything with just 'if': { something_if_true for key, value…
diegueus9
  • 29,351
  • 16
  • 62
  • 74
71
votes
7 answers

Return copy of dictionary excluding specified keys

I want to make a function that returns a copy of a dictionary excluding keys specified in a list. Considering this dictionary: my_dict = { "keyA": 1, "keyB": 2, "keyC": 3 } A call to without_keys(my_dict, ['keyB', 'keyC']) should…
Juicy
  • 11,840
  • 35
  • 123
  • 212
67
votes
3 answers

OrderedDict comprehensions

Can I extend syntax in python for dict comprehensions for other dicts, like the OrderedDict in collections module or my own types which inherit from dict? Just rebinding the dict name obviously doesn't work, the {key: value} comprehension syntax…
wim
  • 338,267
  • 99
  • 616
  • 750
47
votes
2 answers

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

I don't come from a software/computer science background but I love to code in Python and can generally understand why things are faster. I am really curious to know why this for loop runs faster than the dictionary comprehension. Any insights?…
41
votes
3 answers

Selecting elements of a Python dictionary greater than a certain value

I need to select elements of a dictionary of a certain value or greater. I am aware of how to do this with lists, Return list of items in list greater than some value. But I am not sure how to translate that into something functional for a…
Jesse O
  • 421
  • 1
  • 4
  • 4
39
votes
3 answers

Nested dictionary comprehension python

I'm having trouble understanding nested dictionary comprehensions in Python 3. The result I'm getting from the example below outputs the correct structure without error, but only includes one of the inner key: value pairs. I haven't found an…
38
votes
3 answers

Build Dictionary in Python Loop - List and Dictionary Comprehensions

I'm playing with some loops in python. I am quite familiar with using the "for" loop: for x in y: do something You can also create a simple list using a loop: i = [] for x in y: i.append(x) and then I recently discovered a nice efficient…
Mike
  • 4,099
  • 17
  • 61
  • 83
36
votes
4 answers

multiple key value pairs in dict comprehension

I am trying to create multiple key : value pairs in a dict comprehension like this: {'ID': (e[0]), 'post_author': (e[1]) for e in wp_users} I am receiving "missing ','" I have also tried it this way: [{'ID': (e[0]), 'post_author': (e[1])} for e in…
mdxprograms
  • 431
  • 1
  • 4
  • 8
34
votes
1 answer

Alternative to dict comprehension prior to Python 2.7

How can I make the following functionality compatible with versions of Python earlier than Python 2.7? gwfuncs = [reboot, flush_macs, flush_cache, new_gw, revert_gw, send_log] gw_func_dict = {chr(2**i): func for i, func in…
stdcerr
  • 13,725
  • 25
  • 71
  • 128
24
votes
4 answers

Filter out elements that occur less times than a minimum threshold

After trying to count the occurrences of an element in a list using the below code from collections import Counter A = ['a','a','a','b','c','b','c','b','a'] A = Counter(A) min_threshold = 3 After calling Counter on A above, a counter object like…
22
votes
1 answer

Dictionary/set comprehensions inside of f-string

Is it possible to have a dictionary or set comprehension inside of an f-string in python 3.6+? It seems syntactically impossible: names = ['a', 'b', 'c'] pks = [1, 2, 3] f"{{name : pk for name, pk in zip(names, pks)}}" This will return: {name :…
22
votes
3 answers

Is a python dict comprehension always "last wins" if there are duplicate keys

If I create a python dictionary with a dict comprehension, but there are duplicate keys, am I guaranteed that the last item will be the one that ends up in the final dictionary? It's not clear to me from looking at…
user2667066
  • 1,867
  • 2
  • 19
  • 30
21
votes
4 answers

Iterate over a dictionary by comprehension and get a dictionary

How to iterate over a dictionary by dictionary comprehension to process it. >>> mime_types={ '.xbm': 'image/x-xbitmap', '.dwg': 'image/vnd.dwg', '.fst': 'image/vnd.fst', '.tif': 'image/tiff', '.gif': 'image/gif', '.ras':…
Laxmikant Ratnaparkhi
  • 4,745
  • 5
  • 33
  • 49
1
2 3
57 58