[Solved] use dictionary as a list in python


Maybe you can consider using random.sample like so.

>>> import random
>>> p = 2*['a'] + 3*['b'] + 4*['c'] + 5*['d']
>>> random.sample(p, 3)
['b', 'b', 'a']

From the docs, random.sample returns a k length list of unique elements chosen from the population sequence or set. It is used for random sampling without replacement. Therefore, the largest sample you can get from a population of size 14 is size 14, and a sample of size 14 is guaranteed to be a permutation of p.

Alternatively you can use your method of selecting an integer between 1 and 14 inclusive to make weighted random choices using p like this:

>>> k = random.choice(range(1, 15))
>>> p[k-1]
'b'

or, if you don’t need the “index” of the selected element:

>>> random.choice(p)
'c'

However, note that by using random.choice repeatedly, you will be sampling with replacement (unless you have some mechanism of removing selecting elements from the population). This may be what you want though.

To construct your population p dynamically using your dictionary, you can do something like this:

>>> sum((w*[k] for k, w in dic.items()), [])
['d', 'd', 'd', 'd', 'd', 'a', 'a', 'c', 'c', 'c', 'c', 'b', 'b', 'b']

Note that the letters will not necessarily be in order as shown above! But anyways, you can sort them easily using Python’s built in sorted function.

>>> sum(sorted(w*[k] for k, w in dic.items()), [])
['a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'd', 'd', 'd', 'd', 'd']

solved use dictionary as a list in python