I want to sort my dict
by value, but if I apply this code it doesn’t work (it print only my key-value
pairs without any kind of sorting). If I change key=lambda x: x[1] to x[0]
it correctly sort by key
, so I don’t understand what I’m doing wrong.
My code:
JavaScript
x
21
21
1
from gensim.models.word2vec import Word2Vec
2
from scipy.spatial.distance import cosine
3
4
e_science = Word2Vec.load("clean_corpus_science.model")
5
e_pokemon = Word2Vec.load("clean_corpus_pokemon.model")
6
7
science_vocab = list(e_science.wv.vocab)
8
pokemon_vocab = list(e_pokemon.wv.vocab)
9
10
vocab_intersection = list(set(science_vocab).intersection(set(pokemon_vocab)))
11
12
similarity = []
13
for i in range(0, len(vocab_intersection)):
14
similarity.append(1-cosine(e_science[vocab_intersection[i]], e_pokemon[vocab_intersection[i]]))
15
16
hashmap = {}
17
for i in range(0, len(similarity)):
18
hashmap[vocab_intersection[i]] = {similarity[i]}
19
20
dict(sorted(hashmap.items(), key=lambda x: x[1]))
21
Advertisement
Answer
You’re trying to sort sets, and Python isn’t sure how to order them. Take your scores out of the sets, and then you can sort as expected.
JavaScript
1
2
1
dict(sorted(hashmap.items(), key=lambda x: tuple(x[1])[0]))
2
That’s pretty ugly though, you may want to do the cleanup in a separate step.