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
7
votes
2 answers

Dictionary Comprehension for list values

I want to know if there's a more Pythonic way of doing the following, perhaps using dictionary comprehensions: A = some list D = {} for i,v in enumerate(A): if v in D: D[v].append(i) else: D[v] = [i]
7
votes
2 answers

Paring Down a Dictionary of Lists in Python

I'm working with a dictionary for an anagram program in Python. The keys are tuples of sorted letters, and the values are arrays of the possible words with those letters: wordlist = { ('d', 'g', 'o'): ['dog', 'god'], ('a', 'c', 't'): ['act',…
7
votes
5 answers

Build a dictionary from successful regex matches in python

I'm pretty new to Python, and I'm trying to parse a file. Only certain lines in the file contain data of interest, and I want to end up with a dictionary of the stuff parsed from valid matching lines in the file. The code below works, but it's a…
WiringHarness
  • 362
  • 1
  • 2
  • 10
6
votes
4 answers

Python: Combining unique values in list of dicts where keys are the same?

I'm not sure if I am asking the question in the right way, but this is my issue: I have a list of dicts in the following format: [ {'user': 'joe', 'IndexUsed': 'a'}, {'user': 'joe', 'IndexUsed': 'a'}, {'user': 'joe', 'IndexUsed': 'a'}, {'user':…
6
votes
2 answers

List comprehension loop ordering depends on nesting

I'm looking for alternatives to using comprehensions for nested data structures or ways to get comfortable with nested list comprehensions if possible. Without comprehensions generating a list of items using a nested loop works like this: combos =…
6
votes
1 answer

Why is dict unpacking forbidden in dict comprehension?

I've been playing around with dictionary comprehension, and just as I thought I got the hang of it, I received the error: SyntaxError: dict unpacking cannot be used in dict comprehension This is the example that I tried: a = {'a': 1, 'b': 2} …
Walrus
  • 77
  • 2
  • 4
6
votes
2 answers

Rewrite to dictionary comprehensions

I want to count occurrence of all letters in a word using dictionary. So far I've tried adding to dict in for loop. I wonder is it possible to use dictionary comprehensions? word = "aabcd" occurrence = {} for l in word.lower(): if l in…
Tomonaga
  • 167
  • 1
  • 5
6
votes
2 answers

Ternary expression in dictionary comprehension

I'm trying to invert a dictionary. In the case of many keys having the same value, the new key (old value) should associate with a set of the new values (old keys). I solved the problem, but I'm trying to refactor using dictionary comprehension, and…
6
votes
5 answers

Can python dictionary comprehension be used to create a dictionary of substrings and their locations?

Given a string of characters, I want to create a dictionary of all the n-character substrings contained in the string, where the dictionary key is the substring and the value is a list. The first element of the list is the number of occurrences of…
user3065699
  • 329
  • 1
  • 8
6
votes
9 answers

creating dict where keys are alphabet letters and values are 1-26 using dict comprehension

alphaValueDict = OrderedDict.fromkeys(string.ascii_uppercase,range(0) i = 1 for k,v in alphaValueDict.iteritems(): alphaValueDict[k] = [i] i += 1 return alphaValueDict I need to create an ordered dict , where the keys are all the letters in…
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
6
votes
1 answer

How to use Python left outer join using FOR/LIST/DICTIONARY comprehensions (not SQL)?

I have two tuples, details below: t1 = [ ['aa'], ['ff'], ['er'] ] t2 = [ ['aa', 11,], ['er', 99,] ] and I would like to get results like these below using python method similar to SQL's LEFT OUTER JOIN: res = [ ['aa', 11,], ['ff', 0,], ['er',…
5
votes
1 answer

List of tuples to dictionary with duplicates keys via list comprehension?

I have a list of tuples with duplicates and I've converted them to a dictionary using this code I found here: https://stackoverflow.com/a/61201134/2415706 mylist = [(a,1),(a,2),(b,3)] result = {} for i in mylist: …
user2415706
  • 932
  • 1
  • 7
  • 19
5
votes
4 answers

Is it possible to have optional keys in a dict literal?

Is it possible to have 'optional' keys in a dict literal, rather than add them in in if statements? Like so: a = True b = False c = True d = False obj = { "do_a": "args for a" if a, "do_b": "args for b" if b, "do_c": "args for c" if c, …
JamEnergy
  • 720
  • 8
  • 21
5
votes
1 answer

mypy and nested dict comprehension

I'm definitely not an expert of mypy, but there's an error that I'm really not understanding. Let's say that I have this dictionary and I want to parse it and create another one through a dict comprehension. my_dict = { 'type1': { …
5
votes
2 answers

Is it possible to construct a dictionary comprehension from a list of unparsed strings without double split?

Consider the following dictionary comprehension: foo = ['super capital=BLUE', 'super foo=RED'] patternMap = {x.split("=")[0]:x.split("=")[1] for x in foo} It is fairly concise, but I don't like the fact that I need to call x.split('=') twice. I…
merlin2011
  • 71,677
  • 44
  • 195
  • 329
1 2
3
57 58