Python

Keys and Their Values – Dictionary in Python

Pinterest LinkedIn Tumblr

What is Dictionary

Just like a traditional dictionary has words and their meanings. A dictionary is a data structure that contains data in the form of pairs of keys and values. A key and value pair form an item in the dictionary. A key is usually a string.

A dictionary is a collection of key-value pairs. Each key is unique and associated with a value, similar to a real-world dictionary where words (keys) are associated with definitions (values).

Dictionaries are created using curly braces {} or the dict() constructor and keys and values are separated by colons :.

Creating a dictionary

Items in a dictionary are separated by a comma. Note that the last item doesn’t have a comma following it. Keys and values are separated by a colon (:). Items in a dictionary are enclosed within curly brackets.

Here’s an example of how to create a dictionary in Python:

# Creating a dictionary with key-value pairs
my_dict = {'name': 'John', 'age': 30, 'gender': 'Male'}

# Printing the dictionary
print(my_dict)

This creates a dictionary with three key-value pairs. The keys are ‘name’, ‘age’, and ‘gender’, and the values are ‘John’, 30, and ‘Male’, respectively.

You can also create an empty dictionary and add key-value pairs later:

# Creating an empty dictionary
my_dict = {}

# Adding key-value pairs
my_dict['name'] = 'John'
my_dict['age'] = 30
my_dict['gender'] = 'Male'

# Printing the dictionary
print(my_dict)

This creates an empty dictionary, then adds three key-value pairs. The result is the same as the first example.

Accessing data from a dictionary

Accessing data from a dictionary means retrieving the value associated with a specific key in the dictionary.

In Python, you can access a value in a dictionary by using the square bracket [] notation and passing in the key as an argument. For example, given a dictionary with key-value pairs {'name': 'John', 'age': 30, 'gender': 'Male'}, you can access the value associated with the key 'name' like this:

# Accessing a value in a dictionary
my_dict = {'name': 'John', 'age': 30, 'gender': 'Male'}
name = my_dict['name']
print(name)   # Output: 'John'

This code creates a dictionary with three key-value pairs, then retrieves the value associated with the key 'name' and assigns it to a variable named name. The value 'John' is then printed to the console.

If you try to access a key that doesn’t exist in the dictionary, a KeyError will be raised. To avoid this, you can use the get() method to retrieve the value associated with a key, which returns None if the key is not found:

# Using the get() method to access a value in a dictionary
my_dict = {'name': 'John', 'age': 30, 'gender': 'Male'}
occupation = my_dict.get('occupation')
print(occupation)   # Output: None

In this example, the key 'occupation' doesn’t exist in the dictionary, so occupation is assigned the value None.

Updating data in a dictionary

In a dictionary, we can either add a new key-value pair or update an existing one. To update an existing entry we need to first access the item and then assign a new value to it.
For instance,

dict1 = { \n\t‘name’ : ‘xyz’, \n\t‘age’ : 25, \n\t‘hobby’ : ‘Dancing’ \n}

To update the value of ‘name’ we write:

dict1[‘name’] = ‘abc’

That’s it. The name will be updated to contain the value ‘abc’. To add a new key-value pair to the dictionary, we can use a key that is not present in the dictionary and assign a value to it. For instance, writing dict1[‘profession’] = ‘pilot’ will add a new key ‘profession’ with a value ‘pilot’ to dict1.
And now, the updated dict1 will look like.

dict1 = { \n\t‘name’ : ‘xyz’, \n\t‘age’ : 25, \n\t‘hobby’ : ‘Dancing’, \n\t‘Profession’ : ‘pilot’ \n}

Easy:

To update a value in a dictionary, you can use the square bracket [] notation to access the value and then assign a new value to it. For example, given a dictionary with key-value pairs {'name': 'John', 'age': 30, 'gender': 'Male'}, you can update the value associated with the key 'age' like this:

# Updating a value in a dictionary
my_dict = {'name': 'John', 'age': 30, 'gender': 'Male'}
my_dict['age'] = 31
print(my_dict)   # Output: {'name': 'John', 'age': 31, 'gender': 'Male'}

This code creates a dictionary with three key-value pairs, then updates the value associated with the key 'age' to 31. The updated dictionary is then printed to the console.

If the key you’re trying to update doesn’t exist in the dictionary, it will be added as a new key-value pair with the new value. For example:

# Adding a new key-value pair to a dictionary by updating a non-existent key
my_dict = {'name': 'John', 'age': 30, 'gender': 'Male'}
my_dict['occupation'] = 'Engineer'
print(my_dict)   # Output: {'name': 'John', 'age': 30, 'gender': 'Male', 'occupation': 'Engineer'}

In this example, the key 'occupation' doesn’t exist in the dictionary, so updating it with a new value will add it to the dictionary as a new key-value pair.

Deleting data in a dictionary

In a dictionary, we can either remove an individual item or the entire dictionary. To remove an individual item del statement is used followed by the name of the dictionary and the key inside square brackets.

 del dict1[‘name’]

The statement will remove the item with the key ‘name’ from the dictionary.

To remove the entire dictionary, del statement is used followed by the name of the dictionary.

 del dict1

Will delete the entire dictionary.

Instead of deleting the entire dictionary, we can also just remove all the items and empty the dictionary. To do so, we need to use the clear() function.

Writing dict1.clear() will remove all the items from dictionary dict1. If we write print(dict1) after the clear statement. We will get {} as an output, indicating a dictionary with no items.

Simply in Python, deleting data in a dictionary means removing a key-value pair from the dictionary.

To delete a key-value pair from a dictionary, you can use the del statement and specify the key you want to delete. For example, given a dictionary with key-value pairs {'name': 'John', 'age': 30, 'gender': 'Male'}, you can delete the key-value pair associated with the key 'age' like this:

# Deleting a key-value pair from a dictionary
my_dict = {'name': 'John', 'age': 30, 'gender': 'Male'}
del my_dict['age']
print(my_dict)   # Output: {'name': 'John', 'gender': 'Male'}

This code creates a dictionary with three key-value pairs, then deletes the key-value pair associated with the key 'age'. The resulting dictionary only contains the key-value pairs 'name': 'John' and 'gender': 'Male', which are then printed to the console.

If you try to delete a key that doesn’t exist in the dictionary, a KeyError will be raised. To avoid this, you can use the pop() method to remove a key-value pair and return the value associated with the key. For example:

# Using the pop() method to delete a key-value pair from a dictionary
my_dict = {'name': 'John', 'age': 30, 'gender': 'Male'}
age = my_dict.pop('age')
print(age)       # Output: 30
print(my_dict)   # Output: {'name': 'John', 'gender': 'Male'}

In this example, the pop() method is used to remove the key-value pair associated with the key 'age'. The value 30 is returned and assigned to the variable age, and the resulting dictionary only contains the key-value pairs 'name': 'John' and 'gender': 'Male'.

Summary

In summary, a dictionary is a data structure in Python that stores key-value pairs. Keys in a dictionary must be unique and immutable, while values can be of any data type.

You can create a dictionary in Python by enclosing a comma-separated list of key-value pairs in curly braces {} or by using the dict() constructor function. You can also access, update, and delete data in a dictionary using various methods in Python.

To access data in a dictionary, you can use the square bracket [] notation and pass in the key as an argument. To update data in a dictionary, you can use the same notation and assign a new value to the key. To delete data in a dictionary, you can use the del statement to remove a key-value pair or the pop() method to remove a key-value pair and return the value associated with the key.

Dictionaries are a powerful data structure in Python that allow you to store and manipulate data in a flexible and efficient way.

  • We learned a dictionary is a data structure that contains pairs of keys and values separated by a comma and enclosed within curly brackets.
  • To access any item in a dictionary we can use a dictionary name followed by key names inside square brackets.
  • To update any item we first access the item and assign it the value we want.
  • To delete an item we can use del statement followed by the dictionary name and key in brackets.
  • To remove all the items we can use clear() function.
  • And, to delete the entire dictionary we can use del followed by the dictionary name.

Write A Comment