使用Python字典的方法:增删查改实例
在Python中,字典是一种可变容器模型,用于存储键值对。下面我们将通过四个实例来演示字典的增删查改。
创建一个包含键值对的字典
example_dict = {
“Name”: “Alice”,
“Age”: 25,
“Country”: “USA”
}
print(“Example Dictionary:”, example_dict)
2. 增加元素
在字典中添加新的键值对
example_dict[“Job”] = “Software Engineer”
print(“Updated Example Dictionary:”, example_dict)
3. 删除元素
从字典中删除指定的键
if “Country” in example_dict:
del example_dict[“Country”]
print(“Modified Example Dictionary:”, example_dict)
4. 查找元素
查找字典中是否存在特定的键
if “Age” in example_dict:
print(f”‘Age’ is found with value {example_dict[‘Age’]}}”)
else:
print(“‘Age’ not found in the dictionary.”)
或者使用get()方法查找并返回值,如果键不存在则返回默认值(None)
age_value = example_dict.get(“Age”, None)
if age_value:
print(f”‘Age’ is found with value {age_value}}”)
else:
print(“‘Age’ not found in the dictionary.”)
```
以上就是使用Python字典的增删查改实例。
还没有评论,来说两句吧...