After Googling a bit on this and reading a few other SO posts (this one in particular), I can’t seem to find a working solution.
I have a loop as follows:
json_preferred = [] for score, terms in profile.preferred.items(): for term in terms: json_preferred.append({"key": term, "value": score})
Basically I have a dictionary with values that are lists. For each key in the dictionary, I need to create a dictionary in another list that puts the dictionary key and each value as values with fixed keys.
It’s kind of difficult to put into words, but hopefully the code above is a bit more self-explanatory. For context, the output of all of this is a JSON structure that will be used later on in a REST API request.
I want to replace the code above with some kind of list comprehension. However, my attempt at this originally has failed:
json_preferred = [{"key": term, "value": score} for term in terms for score, terms in profile.preferred.items()]
This fails with:
NameError: name ‘terms’ is not defined
dict/list comprehensions greater than 1 dimension are very confusing for me. So I’m not sure what I’m doing wrong here. I’m using Python 3.9.1.
Advertisement
Answer
To form a comprehension, flatten the nested loops and move its body to the beginning of the comprehension:
json_preferred = [] for score, terms in profile.preferred.items(): for term in terms: json_preferred.append({"key": term, "value": score})
…becomes:
json_preferred = [ {"key": term, "value": score} for score, terms in profile.preferred.items() for term in terms ]