Dictionary in python

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 key which is not present in dictionaries, then you get the KeyError.

You can also get the value of key in dictionaries by using get() method.

Example:

user = {
    "name": "John Doe",
    "age": 40,
    "email": 'john@gmail.com'
}

print(user.get("name"))

Output:

John Doe

If you pass key to 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 has 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 following key points:

  1. Dictionary in python is used to store information in formats of key value pairs.
  2. Dictionaries are defined using {}.
  3. keys in dictionaries must have to be unique.
  4. You can access value of keys in dictionaries by passing key in between [].
  5. You can update values in dictionaries by accessing the key and then assigning another value.

Check out Recommended Posts:

Functions in python

Lists in python

Tuples in python

Leave a Reply

Your email address will not be published. Required fields are marked *