python字典中一键多值的写入
作者:野牛程序员:2023-08-13 11:06:27python阅读 2901
在Python中,可以使用列表(List)或集合(Set)作为字典中的值,从而实现一键多值的写入。以下是两种方法的示例:
使用列表(List)作为值:
my_dict = {
'fruits': ['apple', 'banana', 'orange'],
'colors': ['red', 'green', 'blue']
}
# 添加新值到列表中
my_dict['fruits'].append('grape')
# 打印字典
print(my_dict)输出:
{'fruits': ['apple', 'banana', 'orange', 'grape'], 'colors': ['red', 'green', 'blue']}使用集合(Set)作为值(注意:集合会自动去重):
my_dict = {
'fruits': {'apple', 'banana', 'orange'},
'colors': {'red', 'green', 'blue'}
}
# 添加新值到集合中
my_dict['fruits'].add('grape')
# 打印字典
print(my_dict)输出:
{'fruits': {'apple', 'banana', 'orange', 'grape'}, 'colors': {'red', 'green', 'blue'}}无论是使用列表还是集合,都可以像上面的示例一样向字典中的特定键添加新的值。根据需求,选择适合的数据结构来存储一键多值的信息。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:python 打印字典
- 下一篇:python合并字典
