Dictionary in python is used to store information in formats of key-value pairs. Dictionaries are defined using {}. keys in dictionaries must have to be unique. Values in dictionaries can be anything like strings, numbers, boolean, etc.
Example:
user = {
"name": "John Doe",
"age": 40,
"email": 'john@gmail.com'
}
Output:
{‘name’: ‘John Doe’, ‘age’: 40, ’email’: ‘john@gmail.com’}
Accessing the Dictionary:
You can access value of keys in dictionaries by passing key in between [].
Example:
user = {
"name": "John Doe",
"age": 40,
"email": 'john@gmail.com'
}
print(user["name"])
Output:
John Doe
If you pass a key that is not present in dictionaries, then you get the KeyError.
You can also get the value of key in dictionaries by using the get() method.
Example:
user = {
"name": "John Doe",
"age": 40,
"email": 'john@gmail.com'
}
print(user.get("name"))
Output:
John Doe
If you pass the key to the get() method which is not present in dictionaries, then you don’t get any error. You get the value None.
Updating the dictionary:
You can update values in dictionaries by accessing the key and then assigning another value.
Example:
user = {
"name": "John Doe",
"age": 40,
"email": 'john@gmail.com'
}
user["name"] = "Jane Doe"
print(user["name"])
Output:
Jane Doe
Adding new values in the dictionary:
You can also add key values in dictionaries once the dictionaries have defined like following:
Example:
user = {
"name": "John Doe",
"age": 40,
"email": 'john@gmail.com'
}
user["ID"] = 1
print(user)
Output:
{‘name’: ‘John Doe’, ‘age’: 40, ’email’: ‘john@gmail.com’, ‘ID’: 1}
Summary:
In this dictionary in python tutorial, you learned the following key points:
- Dictionary in python is used to store information in formats of key value pairs.
- Dictionaries are defined using {}.
- keys in dictionaries must have to be unique.
- You can access value of keys in dictionaries by passing key in between [].
- You can update values in dictionaries by accessing the key and then assigning another value.