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

Dict comprehension with lambda function and scalar

I have dict comprehension with lambda function and scalar: d = {k: lambda x : x.sum() if 'a' in k else 'yes' for k in ['bac','sss','asa']} print (d) {'bac': . at 0x00000000031891E0>, 'sss': .
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
4
votes
4 answers

Convert nested lists to dictionary in python

I need to convert the nested list result = [[450, 455, 458], [452, 454, 456, 457], [451, 453]] to a dictionary like: { 0: { 450: None, 455: 450, 458: 450 }, 1: { 452:…
Krish V
  • 486
  • 1
  • 5
  • 19
4
votes
3 answers

Removing duplicates in values of dictionary in python

Sorry the topic's title is vague, I find it hard to explain. I have a dictionary in which each value is a list of items. I wish to remove the duplicated items, so that each item will appear minimum times (preferable once) in the lists. Consider the…
L.S
  • 81
  • 6
4
votes
2 answers

Python Set Comprehension Nested in Dict Comprehension

I have a list of tuples, where each tuple contains a string and a number in the form of: [(string_1, num_a), (string_2, num_b), ...] The strings are nonunique, and so are the numbers, e.g. (string_1 , num_m) or (string_9 , num_b) are likely to…
4
votes
2 answers

Python list in list reformatting

What is the pythonic way to reorganize my following data? I have a data data = [ ['a','b',1], ['a','b',2], ['a','b',3], ['a','c',3], ['a','c',4], ['f','g',2], ['f','g',5], ['f','g',9] ] And I want to rearrange it to…
m5seppal
  • 1,186
  • 3
  • 15
  • 31
4
votes
1 answer

Creating a dict with dictionary comprehension and eval() gives me NameError

I am trying to create a dictionary with dictionary comprehensions in the following way (which is part of a much larger code) columns = ['zeta', 'Lm', 'u_mean'] print('zeta', eval('zeta')) print(locals()) dic = {col: [eval(col)] for col in…
TomCho
  • 3,204
  • 6
  • 32
  • 83
4
votes
2 answers

Python -- differences in how I mutate dictionaries in a for loop

I realize that mutating dictionaries while looping over them can cause runtime errors, but I know there are proper ways to do it and I can't figure out which are acceptable and which aren't. Console testing them doesn't help because they MAY…
linus72982
  • 1,418
  • 2
  • 16
  • 31
4
votes
2 answers

Python dictionary comprehension using locals() gives KeyError

>>> a = 1 >>> print { key: locals()[key] for key in ["a"] } Traceback (most recent call last): File "", line 1, in File "", line 1, in KeyError: 'a' How can I create a dictionary with a comprehension like…
J V
  • 11,402
  • 10
  • 52
  • 72
4
votes
1 answer

Julia storing a partitioned data frame to a dictionary

Trying to translate a python script into Julia and Julia seems more than up to it (admittedly I have a very primitive understanding of Julia so I expected some difficulty). In a nutshell, I'm trying to split a data frame by a column vector (that has…
Chase CB
  • 1,561
  • 1
  • 13
  • 20
4
votes
2 answers

How to construct nested dictionary comprehension in Python with correct ordering?

I was trying to shorten the code for this problem when I encountered the problem. Basically, I was trying a nested dictionary comprehension & was unsuccessful in the attempt. Here is what I tried. dict2 = {key:value for key, value in…
shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
4
votes
1 answer

Function arguments not accessible in dict-comprehension

Why does accessing function arguments with eval in a dict comprehension fail? ARGS1 = ('a1', 'b1') def foo1(a1, b1): return {arg:eval(arg) for arg in ARGS1} print foo1("A1", "B1") # NameError: name 'a1' is not defined The same thing in a list…
Lucas Cimon
  • 1,859
  • 2
  • 24
  • 33
3
votes
2 answers

Problem with interlinked dictionaries in Julia

I have a problem regarding values set in a dictionary. I don't understand why they are changed unintentionally within a loop. Here, x_exog["B_l_pre"][2] changed from 0.5 to 0.525, but I only specified x_exog["B_l_post"][2] to change. Why ? ##…
3
votes
0 answers

Assuming the structure of the json string does not change, is the order of a jsonpath match value result stable?

Assuming the structure of the json string does not change, is the order of a jsonpath match value result stable? import jsonpath_ng response = json.loads(response) jsonpath_expression_name =…
Clay Campbell
  • 168
  • 13
3
votes
5 answers

Converting a dictionary of lists to a pandas.DataFrame using predefined headers

I have a dictionary that looks like the following: date_pair_dict = { "15-02-2022 15-02-2022": ["key 1 val 1", "key 1 val 2", "key 1 val 3"], "15-02-2022 16-02-2022": ["key 2 val 1", "key 2 val 2", "key 2 val 3"], "16-02-2022…
ChaddRobertson
  • 605
  • 3
  • 11
  • 30
3
votes
3 answers

Flatten list of dictionaries into dataframe columns

I have the following data which contain lists of dictionaries data= [ {'Time': 18057610.0, 'Flux': [{'V0': -1.4209e-15}, {'V1': 2.7353e-16}, {'V2': 1.1935e-15}, {'V3': 1.1624}, {'V4': -6.1692e-15}, {'V5': 3.2218e-15}]}, {'Time':…