深度阅读

How to create dictionary in python

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

To create a dictionary in Python, you can enclose a sequence of key-value pairs within curly braces , separated by commas:

# create a dictionary with three key-value pairs
my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

# print the dictionary
print(my_dict)

This will output: 'apple': 1, 'banana': 2, 'orange': 3.

You can add new key-value pairs to the dictionary by assigning a value to a new key:

# add a new key-value pair to the dictionary
my_dict['grape'] = 4

# print the updated dictionary
print(my_dict)

This will output: 'apple': 1, 'banana': 2, 'orange': 3, 'grape': 4.

You can also create a dictionary using the built-in dict() function and passing in a sequence of key-value pairs as arguments:

# create a dictionary using the dict() function
my_dict = dict(apple=1, banana=2, orange=3)

# print the dictionary
print(my_dict)

This will output: 'apple': 1, 'banana': 2, 'orange': 3.

相关标签

博客作者

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