As in the code below, I am trying to compute some things and put them into a dictionary. However, as the code below shows, I have to run bct.charpath
multiple times to assign the outputs of the function to different key values, which means that unnecessary computation is required, as the same function will be run multiple times.
Is there a way to define the dictionary so that the bct.charpath
is run only once? (for ex, by defining multiple keys of a dictionary at once??
def scalar_properties(self):
data_dict = {
"char_path_len" : bct.charpath(self.dist_mat)[0],
"global_efficiency" : bct.charpath(self.dist_mat)[1],
"graph_radius" : bct.charpath(self.dist_mat)[3],
"graph_diameter" : bct.charpath(self.dist_mat)[4],
}
return data_dict, data_dict.keys()
(I am aware that I could move the bct.charpath
outside of the dictionary definition and doing sometinag like a, b, c, d, e = bct.charpath(self.dist_mat)
then using those saved a,b,c,d,e, values when defining the dictionary would work. However, I was wondering if there was a cleaner way (with less lines of code) to do this!)
Thank you in advance for your answers!
CodePudding user response:
The answer seems obvious, so I'm wondering what I'm missing.
def scalar_properties(self):
bcp = bct.charpath(self.dist_mat)
data_dict = {
"char_path_len" : bcp[0],
"global_efficiency" : bcp[1],
"graph_radius" : bcp[3],
"graph_diameter" : bcp[4],
}
return data_dict, data_dict.keys()
CodePudding user response:
You can do it using zip
keys = ['char_path_len', 'global_efficiency', 'graph_radius', 'graph_diameter']
data_dict = dict(zip(keys, bct.charpath(self.dist_mat)))