What are Python dictionaries?
Python dictionaries are unordered collections of key-value pairs. This means that each item in a dictionary has a key and a value, and the keys must be unique. Dictionaries are created using curly braces ({}) and can contain any type of data, including integers, floats, strings, lists, and dictionaries.
How to create a Python dictionary
To create a Python dictionary, you simply enclose the key-value pairs in curly braces. For example:
Python
my_dictionary = {"name": "John Doe", "age": 30}
This code creates a dictionary with two key-value pairs: name and age. The key name is associated with the value John Doe, and the key age is associated with the value 30.
How to access items in a Python dictionary
To access items in a Python dictionary, you use the square bracket operator ([]) and the key of the item. For example:
Python
print(my_dictionary["name"]) # Outputs "John Doe"
print(my_dictionary["age"]) # Outputs 30
You can also use the get() method to access items in a dictionary. The get() method takes the key of the item as its argument and returns the value of the item, or None if the key is not in the dictionary. For example:
Python
my_dictionary["occupation"] = "Software Engineer"
print(my_dictionary.get("occupation")) # Outputs "Software Engineer"
print(my_dictionary.get("hobbies")) # Outputs None
How to iterate over a Python dictionary
To iterate over a Python dictionary, you can use the for loop. The for loop iterates over each key in the dictionary and executes a block of code for each key. For example:
Python
for key in my_dictionary:
print(my_dictionary[key])
This code will print the value of each key in the dictionary to the console.
Python dictionary methods
There are a few Python dictionary methods that can be used to perform various tasks on dictionaries, such as adding and removing items from a dictionary, checking if a key is in a dictionary, and getting the keys and values of a dictionary.
Here are some examples of Python dictionary methods:
Here are some additional tips for using Python dictionaries: