深度阅读

How to create a dictionary (also known as a hashmap) in Python

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

To create a dictionary (also known as a hashmap) in Python, you can use curly braces ({}) or the dict() function. Here are some examples:

# Create a dictionary with curly braces
my_dict = {'key1': 'value1', 'key2': 'value2'}
print(my_dict)

# Create a dictionary with the dict() function
my_dict = dict(key1='value1', key2='value2')
print(my_dict)

These will both output 'key1': 'value1', 'key2': 'value2', which is a dictionary with two key-value pairs.

You can also create an empty dictionary and add key-value pairs later:

# Create an empty dictionary
my_dict = {}

# Add a key-value pair
my_dict['key1'] = 'value1'
print(my_dict)

# Add another key-value pair
my_dict['key2'] = 'value2'
print(my_dict)

These will output 'key1': 'value1' and 'key1': 'value1', 'key2': 'value2', respectively, as the key-value pairs are added.

Note that dictionary keys must be immutable (i.e. cannot be changed), so strings, numbers, and tuples are common choices for keys.

相关标签

博客作者

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