In Python, a dictionary is a collection of key-value pairs, where each key is unique. Dictionaries are great as "lookups" as they are implemented using hash tables. To create a dictionary, you can use curly braces {} and separate keys and values with a colon.
For example:
my_dict = {'key1': 'value1', 'key2': 'value2'}
You can also use the built-in dict()
method to create a dictionary:
my_dict = dict(key1='value1', key2='value2')
To access the values in a dictionary, you can use the keys in square brackets, like so:
print(my_dict['key1']) # Output: 'value1'
You can also use the get() method to access the values, which will return None if the key is not found in the dictionary:
print(my_dict.get('key3')) # Output: None
You can add new key-value pairs to the dictionary using the assignment operator:
my_dict['key3'] = 'value3'
You can also update the value of an existing key using the assignment operator:
my_dict['key2'] = 'new_value'
You can also use the update()
method to add multiple key-value pairs at once:
my_dict.update({'key4': 'value4', 'key5': 'value5'})
You can remove key-value pairs from a dictionary using the del keyword or the pop()
method:
del my_dict['key1']
my_dict.pop('key2')
You can iterate through keys and values in a dictionary using a .items()
call:
for key, value in my_dict.items():
print(key, value)
And you can check the length of dictionary by using the .len()
method
len(my_dict)
That is all
I hope you found this helpful, please leave a comment down below if it was!