-1

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?

xralf
  • 3,312
  • 45
  • 129
  • 200

2 Answers2

3

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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

As @Ignacio says, the index choice does correspond to the intended element of lst, so your code's logic is correct. But your code should be much simpler: d already contains IDs for the elements, so rewrite randomWeightedChoice to take a dictionary and return an ID.

Perhaps it will help you to know that you can iterate over a dictionary's key-value pairs with d.items():

for k, v in d.items():
    etc.
alexis
  • 48,685
  • 16
  • 101
  • 161
  • *randomWeightedChoice* takes a list and returns an index from this list. It won't be rewritten. I need to generate exactly 20 random numbers so don't need to iterate over all key-value pairs. – xralf Mar 18 '12 at 13:10
  • You don't have to iterate, that was a demonstration. `randomWeightedChoice` needs to examine all the values in order to do its job, so it has a loop somewhere. If you can't rewrite it, I don't think there's anything else we can help with. – alexis Mar 18 '12 at 13:20
  • Yes, *randomWeightedChoice* needs to examine all the values 20 times to choose 20 random values. – xralf Mar 18 '12 at 13:32
  • No, it doesn't. It only has to examine them once. But what does it matter, if you won't be rewriting it? – alexis Mar 18 '12 at 13:34
  • If I would rewrite this question would have no sense. I'd like to have unique interface instead of having the same function for various data structures (dicts, lists, sets etc.). – xralf Mar 18 '12 at 13:41