Python: Create Empty Dictionary & Add Elements
To create an empty dictionary and add elements, you can use the following method:
- Create an empty dictionary using curly brackets {}, then add key-value pairs to the dictionary using indexing and the assignment operator.
my_dict = {}
my_dict['key1'] = 'value1'
my_dict['key2'] = 'value2'
- Create an empty dictionary using the dict() function, and then add key-value pairs to the dictionary using indexing and assignment operators.
my_dict = dict()
my_dict['key1'] = 'value1'
my_dict['key2'] = 'value2'
- Initialize the dictionary using key-value pairs when defining it.
my_dict = {'key1': 'value1', 'key2': 'value2'}
You can create an empty dictionary and add elements no matter which method you choose.