Search code examples
pythonlistdictionaryindices

Correspendence between list indices originated from dictionary


I wrote the below code working with dictionary and list:

d = computeRanks() # dictionary of id : interestRank pairs
lst = list(d) # tuples (id, interestRank)
interestingIds = []
for i in range(20): # choice randomly 20 highly ranked ids
  choice = randomWeightedChoice(d.values()) # returns random index from list
  interestingIds.append(lst[choice][0])

There seems to be possible error because I'm not sure if there is a correspondence between indices in lst and d.values().

Do you know how to write this better?


Solution

  • One of the policies of dict is that the results of dict.keys() and dict.values() will correspond so long as the contents of the dictionary are not modified.