如何从包含字典的列表中随机获取一个字典并打印输出
随机获取列表中的字典并格式化输出
要实现随机选取列表里的单个字典并按指定格式输出,你可以用Python的random模块里的choice()方法,操作步骤很简单:
- 先导入
random模块,它专门用来处理随机相关的操作 - 用
random.choice(data)从你的data列表里随机挑出一个字典 - 从选中的字典里提取
name、follower_count、description、country这几个字段的值,再按示例格式拼接输出
完整代码如下:
import random data = [ { 'name': 'Instagram', 'follower_count': 346, 'description': 'Social media platform', 'country': 'United States' }, { 'name': 'Cristiano Ronaldo', 'follower_count': 215, 'description': 'Footballer', 'country': 'Portugal' }, { 'name': 'Ariana Grande', 'follower_count': 183, 'description': 'Musician and actress', 'country': 'United States' } ] # 随机选择一个字典 random_item = random.choice(data) # 按指定格式输出 print(f"{random_item['name']}, {random_item['follower_count']}, {random_item['description']}, {random_item['country']}")
运行这段代码,每次执行都会随机输出列表里的某一项,比如Cristiano Ronaldo, 215, Footballer, Portugal或者其他符合格式的条目。
内容的提问来源于stack exchange,提问作者SolidOpt
相关产品推荐
相关产品推荐

