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

Pythonic way toCompare two Dictionaries and Append Nested Object where keys match

Python newbie with working code, but looking to learn if there is a better way. Problem statement - One python dictionary contains details about volumes, and a second contains details about snapshots of the volumes. Produce a json document with…
2
votes
3 answers

How to change the key and value of a dictionary

So I've got the following code, and what I want to do is take every second value of the inputted tuple, and save it to a dictionary as the dict.key, and the dict.value set at first to 0. After that I want to go over the saved dictionary and for…
2
votes
1 answer

Removing element from a list in a for loop

I have a list that has lists with dictionaries in them. I'm trying to check one of the values for a key inside the dictionary and if it's try then I remove that list from the list. I'm getting a bit confused with the layers of lists and dictionaries…
2
votes
2 answers

Nested dictionary comprehension (2 level)

I have a list of dictionary objects data = [ { 'id': 1, 'parent_id': 101 , 'name': 'A' }, { 'id': 2, 'parent_id': 101, 'name': 'B' }, { 'id': 3, …
2
votes
0 answers

How to create a group | sub-group (pre-defined) cyclic order by considering the identical consecutive groupings (in Pandas DataFrame) columns?

Task 1: I am looking for a solution to create a group by considering the identical consecutive groupings in one of the columns (of my Panda's DataFrame, ..considering this as values of a list): from itertools import groupby test_list = ['AA', 'AA',…
2
votes
3 answers

build a dict using dictionay-comprehension when I get keys and values from the same function

Let's assume I have a complex function get_stuff that takes an int and returns a tuple, the 1st element is of type str. The following example has the same behavior but assume the real function is more complex and can't easily be split in two: def…
Anne Aunyme
  • 506
  • 4
  • 14
2
votes
3 answers

How to parse a file and populate a python dictionary with its content

So I have the following file summary1: --- Project: pgm1 Last-Status: success summary: 102 passed, 88 warnings in 26.11s --- Project: pgm2 Last-Status: failed summary: 1 failed, 316 passed, 204 warnings in 42.94s --- Project: pgm3 Last-Status:…
2
votes
2 answers

Using a dictionary comprehension with an included string split operation

Consider a tiny properties parser snippet: testx="""var1 = foo var2 = bar""" dd = { l.split('=')[0].strip():l.split('=')[1].strip() for l in testx.split('\n')} print(dd) # {'var1': 'foo', 'var2': 'bar'} That works , but is ugly due to…
WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
2
votes
1 answer

Dictionary comprehension matching values?

I have this dictionary: Dict1= {'0': [('L', 'Any'), ('D', 'Any')], '1': [('D', 'Any'), ('E', 'Any'), ('D', 'Any')]} and this one: Dict2= {'0': ['0', '1', '2'], '1': ['0', '1', '2'], '2': ['0', '1', '2'], '3': ['0', '1', '2']} I would like to…
2
votes
2 answers

Create dictionary from a nested list

I have a nested list that looks like this: my_list = [['Raji GlovesSixSixOneRegular price', 'Sale price$9.95', ' Save 67%'], ['Comp Vortex GlovesSixSixOneRegular price', 'Sale price$9.95', ' Save 67%'], …
NewBee
  • 990
  • 1
  • 7
  • 26
2
votes
5 answers

How to generate dictionaries from multiple lists?

I have the following lists : valuevalues = [4, 5, 35, 23, 16, 7, 12] labelvalues = ['john', 'joe', 'Pier', 'Paul', 'Moe', 'Jane', 'Ruth'] labels = ['label' for i in range(len(valuevalues))] values = ['value' for i in range(len(valuevalues))] And I…
2
votes
4 answers

Python3 Dictionary Comprehension

I'm having difficulty working out a dictionary comprehension. I have a list of dictionaries, where each dictionary contains identical keys with different values: list_of_dictionaries = [{k1:v1, k2:v2}{k1:v3, k2:v4}{k1:v5, k2:v6}, ...] I would…
jackmoar
  • 23
  • 3
2
votes
2 answers

Python list and dictionary comprehension

I am trying to get use to list dictionaries comprehension. Here a small code I have not been able to transform. lst = ['C', 'A', 'B', 'A'] myd = {} for v, k in enumerate(lst): if k in myd: myd[k].append(v) else: myd[k] =…
2
votes
3 answers

Deep copy of dictionary created with comprehension not working

Could you please help me understand why does deepcopy not work for all the elements in the dictionary from the example below? import copy a = [{'id':1, 'list':[1,2,3], 'num':3}, {'id':2,' list':[4,5,6], 'num':65}] b = {i['id']:copy.deepcopy(i) for i…
Matteo
  • 7,924
  • 24
  • 84
  • 129
2
votes
2 answers

Applying list values to a list of dictionaries

Let's say I have a list of dictionaries that look like this: final_list = [{'city': 'value', 'population': 'value'}, {'city': 'value', 'population': 'value'}, {'city': 'value', 'population': 'value'}] And I have a list of lists that looks like…