How to create dictionary in python
Published on Aug. 22, 2023, 12:16 p.m.
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
.