理解Python字典的特性以及操作案例
Python字典是可变容器模型,它由键值对(key-value pair)组成。以下是字典的一些基本特性:
通过键访问值:Python字典中每个元素都由一个唯一键和对应的值组成。
dict_example = {"name": "John", "age": 30}
print(dict_example["name"]) # 输出: John
添加/更新元素:可以使用
dict[key] = value
或者dict.update({key: value})
来添加或更新键值对。dict_example = {"name": "John", "age": 30}
dict_example["city"] = "New York"
print(dict_example) # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}
删除元素:使用
del dict[key]
或dict.pop(key)
来删除指定键的值。dict_example = {"name": "John", "age": 30}
del dict_example["age"]
print(dict_example) # 输出: {'name': 'John', 'age': None}
字典的遍历:可以使用for循环遍历字典的所有键值对,或者使用
items()
方法。dict_example = {"name": "John", "age": 30}
for key, value in dict_example.items():
print(f"{key}: {value}")
以上就是Python字典的一些特性以及操作案例。
还没有评论,来说两句吧...