How can I assign a set of random values as values to a dicionary?

Question:

import random


def sample() -> None:
    file_name = "something" + '.txt'
    with open('C:/Users/xyz/PycharmProjects/some/{0}'.format(file_name), 'w') as f:
        shop_list = [Fruit_shop, Games_shop, Dress_Shop]
        random_shop = random.choice(shop_list)
        for key, value in random_shop.items():
            f.write(key + 'n')
            for key1, value1 in value.items():
                f.write(f"{key1} :={value1}n")
            f.write(f"{'}'}")
            f.write(f"nn")

Fruit_shop = {
    'Fruits {':{
        'A':'Apple',
        'B':'Ball'
    }
}
Games_shop = {
    'Games {':{
        'A':'Cricket',
        'B':'Football'
    }
}

Dress_Shop = {
    'Dresses {':{
        'A':'Jeans',
        'B':'Shirts'
    }
}
sample()

Expecting an output something like this:-
1st Iteration –

Fruits {
A :=Apple
B :=Ball
}

2nd iteration –

Games{
A :=Jeans
B :=Shirts
}

3rd itertation –

Dresses{
A :=Cricket
B :=Football
}

Whenever the above code is run, with each iteration I want the value of A to be either Apple or Cricket or Jeans, similarly B: Ball or Football or Shirts, I think we need to use the random module here, can any one help me how to do that please? Thanks in Advance!

Asked By: abhishekravoor

||

Answers:

I think the following should do what you are after:

import random

shops = ["Fruit", "Games", "Dresses"]
productA = ["Apple", "Jeans", "Cricket"]
productB = ["Ball", "Shirts", "Football"]

def sample(shops, productA, productB, outputfile="something.txt"):
    with open(outputfile, "w") as fp:
        shop = random.choice(shops)  # pick random shop
        prodA = random.choice(productA)  # pick random product A
        prodB = random.choice(productB)  # pick random product B

        shopdict = {"A": prodA, "B": prodB}
        fp.write(shop)
        fp.write("{n")
        for key, value in shopdict.items():
            fp.write(f"{key} :={value}n")
        fp.write("}n")

sample(shops, productA, productB)
Answered By: Matt Pitkin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.