Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

sorting - Sort dictionary python by value (word2vec)

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:

from gensim.models.word2vec import Word2Vec
from scipy.spatial.distance import cosine

e_science = Word2Vec.load("clean_corpus_science.model")
e_pokemon = Word2Vec.load("clean_corpus_pokemon.model")

science_vocab = list(e_science.wv.vocab)
pokemon_vocab = list(e_pokemon.wv.vocab)

vocab_intersection = list(set(science_vocab).intersection(set(pokemon_vocab)))

similarity = []
for i in range(0, len(vocab_intersection)):
  similarity.append(1-cosine(e_science[vocab_intersection[i]], e_pokemon[vocab_intersection[i]]))

hashmap = {}
for i in range(0, len(similarity)):
  hashmap[vocab_intersection[i]] = {similarity[i]} 

dict(sorted(hashmap.items(), key=lambda x: x[1]))
question from:https://stackoverflow.com/questions/65925841/sort-dictionary-python-by-value-word2vec

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

dict(sorted(hashmap.items(), key=lambda x: tuple(x[1])[0]))

That's pretty ugly though, you may want to do the cleanup in a separate step.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...