Chaitanya
Chaitanya

Reputation: 1610

Error in selecting random item from Dictionary in python

I wan't to create a program that select 2 random items from two different dictionaries. Now I wan't to check if the sum of those items is equal to the value provided by the User. And i wan't to perform this action until i find 2 random items from different dictionaries that add up to the number entered by the User.

Here is what i tried to do:

import random
credit=int(raw_input("Please enter your amount: "))
food=dict([(10, 'Lays'), (10,'Pepsi'), (10,'Burger')])
toys=dict([(10, 'Car'), (10,'Train'), (10,'Chess')])
ranf=random.choice(food.keys())
rant=random.choice(toys.keys())
while int(ranf)+int(rant)!=credit:
    ranf=random.choice(food.keys())
    rant=random.choice(toys.keys())
print(ranf)
print(food[ranf])
print(rant)
print(food[rant])

When i try to run this code it fails to print those two random items. I'm not getting any error message. Please run this code and help me out.

Thank You

Upvotes: 0

Views: 162

Answers (2)

user2582048
user2582048

Reputation:

food.keys() only returns unique keys. So, essentially the only list of keys returned by the food.keys() function is [10]. ex if you make a dictionary like food = dict([(10, 'Lays'), (15,'Pepsi'), (15,'Burger')]) then the list returned by food.keys() will be [10,15] and not [10,15,15] which is what you expect. So, in your code, if ranf = 10, then interpreter takes up the latest value assigned to that key.

Therefore, the random.choice() you are using goes in vain. Also, there is a silly mistake in your code, you wrote print(food[rant]) instead of writing print(toys[rant]).

It would be better if you don't use a list, otherwise, make the keys different.

Upvotes: 1

BartoszKP
BartoszKP

Reputation: 35891

The problem lies within the fact, that you create your dictionaries with duplicate keys - effectively, your food dictionary contains only (10,'Burger') and your toys dictionary has only (10,'Chess') item (they both contain only most recently added item, which replaced all the previous ones). The simplest and quickest fix would be to abandon the usage of a dictionary:

import random
credit=20
food=[(10, 'Lays'), (10,'Pepsi'), (10,'Burger')]
toys=[(10, 'Car'), (10,'Train'), (10,'Chess')]
ranf=random.choice(food)
rant=random.choice(toys)
while int(ranf[0])+int(rant[0])!=credit:
    ranf=random.choice(food)
    rant=random.choice(toys)

print(ranf)
print(rant)

Upvotes: 3

Related Questions