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
20
votes
4 answers

What is the equivalent of Python list, set, and map comprehensions in Kotlin?

In Python, there are list comprehensions and similar constructs for maps and sets. In Kotlin there is nothing at all in any of the documentation with a similar name. What are the equivalents of these comprehensions? For example, those found in…
Jayson Minard
  • 84,842
  • 38
  • 184
  • 227
15
votes
4 answers

How can i count occurrence of each word in document using Dictionary comprehension

I have a list of lists in python full of texts. It is like set words from each document. So for every document i have a list and then on list for all documents. All the list contains only unique words. My purpose is to count occurrence of each word…
Pappu Jha
  • 477
  • 1
  • 3
  • 14
14
votes
7 answers

Expand a dict containing list items into a list of dict pairs

If I have a dictionary containing lists in one or more of its values: data = { 'a':0, 'b':1, 'c':[0, 1, 2], 'pair':['one','two'] } How can I get a list of dict tuples paired by pair and iterating over c, with all else remaining constant?…
14
votes
8 answers

Python - tuple unpacking in dict comprehension

I'm trying to write a function that turns strings of the form 'A=5, b=7' into a dict {'A': 5, 'b': 7}. The following code snippets are what happen inside the main for loop - they turn a single part of the string into a single dict element. This is…
13
votes
2 answers

Using ordered dictionary as ordered set

Now that Python 3.7 makes order-preserving dicts officially part of the language spec instead of an implementation detail, I've been trying to wrap my head around how best to use this property. Today, I've found I needed an order preserving set and…
12
votes
4 answers

Find count of characters within the string in Python

I am trying to create a dictionary of word and number of times it is repeating in string. Say suppose if string is like below str1 = "aabbaba" I want to create a dictionary like this word_count = {'a':4,'b':3} I am trying to use dictionary…
Chiyaan Suraj
  • 1,021
  • 2
  • 13
  • 27
12
votes
0 answers

Why does this python code exhibit weird scoping rules

I'm running on Python 2.7.8 (Anaconda Distribution) and this code fails. This looks like a bug in the Python implementation, but am I missing anything? class C: x = {2 : 1} y = {w for w in x if x[w]==1} Running this code gives the following…
12
votes
2 answers

Python--Finding Parent Keys for a specific value in a nested dictionary

I am struggling to process a nested dictionary, and return the nested Parent Keys, for a specific Value, when the Value may exist more than once in the nested dictionary. For example: example_dict = { 'key1' : 'value1', 'key2' :…
Mike
  • 133
  • 2
  • 5
11
votes
6 answers

Is it possible to access current object while doing list/dict comprehension in Python?

I'm trying to think of a one-liner to achieve the following (summing all the values of a key): >>> data = [('a', 1), ('b', 3), ('a', 4), ('c', 9), ('b', 1), ('d', 3)] >>> res = {} >>> for tup in data: ... res[tup[0]] = res.setdefault(tup[0], 0)…
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
11
votes
2 answers

Conditional expressions in Python Dictionary comprehensions

a = {"hello" : "world", "cat":"bat"} # Trying to achieve this # Form a new dictionary only with keys with "hello" and their values b = {"hello" : "world"} # This didn't work b = dict( (key, value) if key == "hello" for (key, value) in…
user462455
  • 12,838
  • 18
  • 65
  • 96
10
votes
2 answers

walrus operator in dict comprehension

I wanted to avoid double evaluation of a mean in a dict comprehension, and I tried using the walrus operator: >>> dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]} >>> q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in…
9
votes
2 answers

Python list comprehension with dummy names identical to iterator name: ill-advised?

Say I make a list comprehension that looks something like this: i = range(5) a = [f(i) for i in i] for some function f. Will using a dummy name identical to the iterator ever yield unexpected results? Sometimes I have variable names that are…
9
votes
3 answers

Python3: Conditional extraction of keys from a dictionary with comprehension

I need to extract those keys of a dictionary whose values pass a certain condition. Basically, I want to do this, only in a shorter, more pythony way: keys=[] for key in dict: if dict[key]==True: keys.append(key) This was my original…
purrduc
  • 135
  • 1
  • 5
9
votes
1 answer

Problems when using dict comprehensions. NameError: global name is not defined

I am trying to create a dict with key as name and value as corresponding User object. I am using Python shell from Django shell wrapper python manage.py shell: >>> from django.contrib.auth.models import User >>> names = ['carl', 'jim', 'jack',…
7
votes
1 answer

Python: append to value-list using dictionary-comprehension

I have the following scenario - consider the list of dictionaries as below (input): data = [{'key1' : 'k1v1', 'key2': 'k2v1'}, {'key1': 'k1v2', 'key2': 'k2v2'}, {'key1': 'k1v3', 'key2': 'k2v3'}, {'key1': 'k1v4', 'key2': 'k2v4'}] As can be…
anurag
  • 1,715
  • 1
  • 8
  • 28
1
2
3
57 58