Reputation: 7208
I have below code:
for i in range(len(known_embeddings["embeddings"])):
known_vec = known_embeddings["embeddings"][i]
vec = vec.reshape(-1, 1)
distance = cv2.norm(vec, known_vec)
print("name : {}, distance : {}".format(known_embeddings["names"][i], distance))
In above code known_embeddings
is dict of list which contains embeddings
and names
as list. The output of above code is :
name : mark, distance : 0.8483050632128444
name : mark, distance : 0.8724386372273983
name : mark, distance : 0.7805887577479304
name : mark, distance : 1.1670809288281123
name : mark, distance : 0.7298390620115697
name : tom, distance : 0.8128083541249622
name : tom, distance : 1.1103164155361172
name : tom, distance : 1.0548001777991225
name : tom, distance : 1.265357138869811
name : tom, distance : 1.2954636861331879
where each name contains a value of distance. Now I want to save above result into a dict of list or may be two different list so that I can later compare the values of each index of both the names. How can I save it in dict of list.? Thanks
Upvotes: 0
Views: 52
Reputation: 236004
I took the liberty of simplifying a bit your code. Please try this:
from collections import defaultdict
d = defaultdict(list)
vec = vec.reshape(-1, 1)
for name, embedding in zip(known_embeddings["names"], known_embeddings["embeddings"]):
distance = cv2.norm(vec, embedding)
d[name].append(distance)
Because you have multiple values (distances) for the same key (name), we need to append them to a list, and defaultdict
comes in handy just for that, for initializing each key with an empty list so it's safe to append values to it..
Upvotes: 2
Reputation: 134
Instead of the loop that ends with
print("name : {}, distance : {}".format(known_embeddings["names"][i], distance))
try this:
my_dictionary = {knownembeddings["names"][i] : cv2.norm(vec.reshape(-1, 1), known_embeddings["embeddings"][i]) for i in range(len(known_embeddings["embeddings"]))}
Upvotes: 1