在Python中,如何将一组随机值作为值对分配给字典数据结构?

2w2cym1i  于 2023-06-07  发布在  Python
关注(0)|答案(1)|浏览(165)
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"\n\n")

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

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

期望输出如下所示:-第一次迭代-

Fruits {
A :=Apple
B :=Ball
}

第二次迭代-

Games{
A :=Jeans
B :=Shirts
}

第三次迭代-

Dresses{
A :=Cricket
B :=Football
}

每当上面的代码运行时,每次迭代我都希望A的值是Apple或Cricket或Jeans,类似地B:球或足球或衬衫,我想我们需要使用随机模块在这里,可以任何一个帮助我如何做到这一点?提前感谢!

kd3sttzy

kd3sttzy1#

我认为以下应该做你所追求的:

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)

相关问题