以下是在 Python 中创建一个字典并添加键值对的几种方法:
# 方法一:使用花括号直接创建字典,并添加键值对
my_dict = {}
my_dict['key1'] = 'value1'
my_dict['key2'] = 'value2'
print(my_dict)
# 方法二:使用 dict() 函数创建字典,并添加键值对
another_dict = dict()
another_dict['name'] = 'Alice'
another_dict['age'] = 25
print(another_dict)
# 方法三:创建字典时直接添加键值对
third_dict = {'fruit': 'apple', 'color': 'red'}
third_dict['shape'] = 'round'
print(third_dict)
代码解释:
- 方法一:首先,
my_dict = {}
创建了一个空的字典。然后,通过my_dict['key1'] = 'value1'
这种方式添加键值对,将'key1'
作为键,'value1'
作为对应的值存储在字典中。同理可以添加更多键值对。 - 方法二:
another_dict = dict()
也是创建了一个空字典,后续使用相同的[键] = 值
的方式添加键值对。 - 方法三:在创建字典
third_dict = {'fruit': 'apple', 'color': 'red'}
时,直接初始化了一些键值对,之后使用third_dict['shape'] = 'round'
继续添加新的键值对。
你可以根据自己的需求选择上述的一种或多种方法来创建并向字典添加键值对。需要注意的是,字典中的键必须是唯一的,如果使用相同的键添加新值,会覆盖原来的值,例如:
my_dict = {'a': 1}
my_dict['a'] = 2
print(my_dict) # 输出:{'a': 2}
这是因为字典是通过键来存储和检索数据的,同一个键只能对应一个值。