Python dictionaries

Created By: chatGPT

In Python, a dictionary is an unordered collection of items. Each item is stored as a pair of a key and a value. This structure allows for fast access and modification of data. You can create a dictionary using curly braces {}, with the key-value pairs separated by commas.
my_dict = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}
To access a value in a dictionary, you can use its corresponding key inside square brackets []. If the key does not exist, a KeyError will be raised.
print(my_dict['name'])  # Output: John
You can also use the .get() method, which will return None (or a default value you specify) if the key is not found, thus avoiding an error.
print(my_dict.get('country', 'Not Found'))  # Output: Not Found
To add or update an item in a dictionary, you simply assign a value to a key. If the key exists, it updates the value; if not, it creates a new key-value pair.
my_dict['age'] = 31  # Update the existing key
my_dict['country'] = 'USA'  # Add a new key
To remove an item, you can use the del statement or the .pop() method. The del statement removes the item without returning it, while .pop() removes the item and returns its value.
del my_dict['city']  # Removes 'city'
removed_value = my_dict.pop('age')  # Returns 31 and removes 'age'
You can iterate over a dictionary using a for loop to access the keys, values, or both. Using .items() allows you to loop through key-value pairs directly.
for key, value in my_dict.items():
    print(key, value)
Dictionaries are mutable, meaning that you can change their content without changing the identity of the object. This makes them a powerful tool for dynamic data storage and manipulation in Python.
# Original dictionary
print(my_dict)
# After modifications
my_dict['name'] = 'Alice'
print(my_dict)
There are also several built-in methods associated with dictionaries such as .keys(), .values(), and .items(), which help you retrieve the keys, values, or key-value pairs respectively.
keys = my_dict.keys()
values = my_dict.values()
items = my_dict.items()
Introduction And SetupVariablesData TypesIntFloatStrBoolListTupleSetDictMethodsString MethodsList MethodsDict MethodsSet MethodsControl FlowIf StatementElif StatementElse StatementFor LoopWhile LoopBreak StatementContinue StatementFunctionsDef StatementReturn StatementLambda FunctionsScopeParametersArgumentsDefault ParametersVariable Length ArgumentsOperatorsArithmetic OperatorsComparison OperatorsLogical OperatorsAssignment OperatorsIdentity OperatorsMembership OperatorsData StructuresListsTuplesSetsDictionariesCommentsSingle Line CommentsMulti Line CommentsSyntaxIndentationDocstringsEvent HandlingError HandlingTry StatementExcept StatementFinally StatementRaise StatementAssert StatementContext ManagersWith Statement