Jack
Jack

Reputation: 371

From a dictionary made of multiple lists choose one element from each

Lets say I have a dictionary of lists like this:

lists= {'pet': ["dog", "cat", "parrot"],
        'amount': [1,2,3],
        'food': ["canned", "dry"]}

And I want to pick one element from each list, randomly, so the result is like this:

{'amount': 2, 'food': 'canned', 'pet': 'cat'}

Which would the simplest way to achieve it using Python?

Upvotes: 1

Views: 48

Answers (1)

cs95
cs95

Reputation: 402593

Have you tried random.choice?

from random import choice

{k: choice(v) for k in lists.items()}  # use lists.iteritems() in python 2.x 
# {'pet': 'parrot', 'amount': 3, 'food': 'canned'}

Or, if you want to update lists in-place, use

for k, v in lists.items():
    lists[k] = choice(v)

lists
# {'pet': 'parrot', 'amount': 3, 'food': 'canned'}

Alternatively, if you have a version of python that supports ordered builtin dictionaries (>= cpython3.6, >= python3.7), you can try using map as a functional alternative:

dict(zip(lists, map(choice, lists.values())))
# {'pet': 'parrot', 'amount': 2, 'food': 'dry'}

Personally I like the first two options though.

Upvotes: 6

Related Questions