深度阅读

How to add a new key-value pair item to a dictionary in Python

作者
作者
2023年08月22日
更新时间
9.86 分钟
阅读时间
0
阅读量

To add a new key-value pair item to a dictionary in Python, you can use either of the following methods:

  1. Dictionary indexing:
my_dict = {'apple': 1, 'banana': 2}
my_dict['orange'] = 3

This will add the key-value pair ('orange', 3) to the dictionary my_dict.
2. The dict.update() method:

my_dict = {'apple': 1, 'banana': 2}
my_dict.update({'orange': 3})

This will update the dictionary my_dict with the key-value pair ('orange', 3).

Here’s an example of adding a new item to a dictionary using Dictionary indexing:

# Creating a dictionary
fruit_counts = {"apples": 5, "oranges": 8, "bananas": 12}

# Adding a new item to the dictionary
fruit_counts["pears"] = 6
print(fruit_counts)

This will output:

{"apples": 5, "oranges": 8, "bananas": 12, "pears": 6}

Note that if the key already exists in the dictionary, these methods will update the existing value associated with that key rather than adding a new key-value pair.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。