I have a dictionary whose keys are related to list of values, but any value may be related to many keys, hence be contained in various lists-attached-keys.
To highlight such relation; I build (in Python 3.6.1) the reverse dictionary using this:
from collections import defaultdict
#defaultdict is a dict that you set up to output a datatype as default, instead of throwing a KeyError exception, when a key not contained into it is called, it outputs the default datatype and the corresponding key is created on the fly and kept.
reversed_dict =defaultdict(list)
primary_dict ={"abc":[1,2,3], "cde":[3,5,7],"efg":[4,2,1,7]}
#in the call of default dict, you must input a callable
[reversed_dict[term].append(key) for key, innerset in primary_dict.items() for term in innerset]
#append should be used instead of extend, as keys are strings, and extend would result in their breakdown
#desired output for reversed_dict:
#defaultdict(list,
# {1: ['abc', 'efg'],
# 2: ['abc', 'efg'],
# 3: ['abc', 'cde'],
# 4: ['efg'],
# 5: ['cde'],
# 7: ['cde', 'efg']})
The code is very simple, and efficient.
My question is more about using the list comprehension to get the loading of the dict
done, while it is not assigned to anything. Can't this cause any sort of problem? Shouldn't I better assign the comprehension and then delete it?
I am not very much used to "leaving in the air" something in Python. So I wonder if it is not "ugly", or problematic. I feel like it is bad because the comprehension is not actually doing what it is intended to, aka creating a list, I am only using its related feature of mimicking a for loop for it, because it is more efficient and readable than such loop.
What do you think?
I have been using such pattern for a long time now, but I was never completely satisfied with it, I only kept it because the other way I found were too convoluted to do this, or not using only one step.
About the context, it is difficult to say because I very often have to use such practice. I am in bioinformatics, so I often get associations between a key (say a gene or protein) and a list (of biological effects, related drugs and so on). Sometimes I use dataframes, but actually I find groupby not very convenient, as to get the related info you have to handle indexes (granted, you can set you keys as index and drop the column, but it is many operations, plus you have an index as output and this comes with its own kind of hassle.
{}
button in the toolbar). \$\endgroup\$the comprehension is not actually doing what it is intended to, aka creating a list
Yes it does. You're just not using it. \$\endgroup\$element in set
isO(1)
whileelement in list
isO(n)
. \$\endgroup\$