Creating a dictionary in Python is easy. A dictionary is a collection of key-value pairs, where each key is associated with a value. The values can be of any data type, and the keys must be unique. Here’s how you can create a dictionary in Python:
# Create an empty dictionary my_dict = {} # Create a dictionary with values my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"} # Add a key-value pair to the dictionary my_dict["key4"] = "value4" # Access a value in the dictionary value = my_dict["key1"]
In the example above, we created an empty dictionary my_dict
using curly braces {}
. We then created a dictionary with three key-value pairs. We added a fourth key-value pair using square brackets []
, and accessed the value of key1
using square brackets []
as well.
You can also use the dict()
constructor to create a dictionary:
# Create a dictionary using dict() my_dict = dict(key1="value1", key2="value2", key3="value3")
In this example, we created a dictionary with three key-value pairs using the dict()
constructor. We specified the keys and values as keyword arguments.
Adding Elements to a Dictionary:
You can add new key-value pairs to an existing dictionary in Python using the following methods:
Method 1: Using square brackets []
You can add a new key-value pair to a dictionary using square brackets []
. If the key already exists, the corresponding value will be updated.
Example:
# Create a dictionary my_dict = {'name': 'John', 'age': 30} # Add a new key-value pair my_dict['gender'] = 'Male' # Display the updated dictionary print(my_dict)
Output:
{'name': 'John', 'age': 30, 'gender': 'Male'}
Method 2: Using the update()
method
You can add multiple key-value pairs to a dictionary using the update()
method. If a key already exists, the corresponding value will be updated.
Example:
# Create a dictionary my_dict = {'name': 'John', 'age': 30} # Add multiple key-value pairs my_dict.update({'gender': 'Male', 'city': 'New York'}) # Display the updated dictionary print(my_dict)
Output:
{'name': 'John', 'age': 30, 'gender': 'Male', 'city': 'New York'}
In both examples, we added new key-value pairs to the existing dictionary using different methods.
Removing Elements from Dictionary:
In Python, you can remove elements from a dictionary using the del
keyword or the pop()
method. Here are the details:
Using del
The del
keyword allows you to remove an element from a dictionary by specifying its key. Here’s the syntax:
del dict[key]
Here, dict
is the name of the dictionary, and key
is the key of the element you want to remove.
Here’s an example:
>>> my_dict = {"apple": 2, "banana": 4, "orange": 1} >>> del my_dict["apple"] >>> print(my_dict) {"banana": 4, "orange": 1}
Using pop()
The pop()
method allows you to remove an element from a dictionary and return its value. Here’s the syntax:
dict.pop(key[, default])
Here, dict
is the name of the dictionary, key
is the key of the element you want to remove, and default
is the value to return if the key is not found (optional).
Here’s an example:
>>> my_dict = {"apple": 2, "banana": 4, "orange": 1} >>> value = my_dict.pop("apple") >>> print(value) 2 >>> print(my_dict) {"banana": 4, "orange": 1}
Note that if you try to remove an element using a key that doesn’t exist in the dictionary, you’ll get a KeyError
(if you use del
) or the default
value (if you use pop()
with a default value).
Python Dictionary Methods:
In Python, dictionaries are a very useful data structure that allow you to store key-value pairs. There are several built-in methods that can be used with dictionaries. Here are some of the most common dictionary methods:
clear()
: Removes all the items from the dictionary.
my_dict = {"apple": 2, "banana": 4, "orange": 1} my_dict.clear() print(my_dict) # Output: {}
copy()
: Returns a shallow copy of the dictionary.
my_dict = {"apple": 2, "banana": 4, "orange": 1} new_dict = my_dict.copy() print(new_dict) # Output: {"apple": 2, "banana": 4, "orange": 1}
get(key[, default])
: Returns the value for the given key. If the key is not found, it returns thedefault
value (which isNone
by default).
my_dict = {"apple": 2, "banana": 4, "orange": 1} print(my_dict.get("apple")) # Output: 2 print(my_dict.get("mango")) # Output: None print(my_dict.get("mango", "No such fruit exists!")) # Output: "No such fruit exists!"
items()
: Returns a view object that contains the key-value pairs of the dictionary.
my_dict = {"apple": 2, "banana": 4, "orange": 1} print(my_dict.items()) # Output: dict_items([('apple', 2), ('banana', 4), ('orange', 1)])
keys()
: Returns a view object that contains the keys of the dictionary.
my_dict = {"apple": 2, "banana": 4, "orange": 1} print(my_dict.keys()) # Output: dict_keys(['apple', 'banana', 'orange'])
values()
: Returns a view object that contains the values of the dictionary.
my_dict = {"apple": 2, "banana": 4, "orange": 1} print(my_dict.values()) # Output: dict_values([2, 4, 1])
pop(key[, default])
: Removes and returns the value for the given key. If the key is not found, it returns thedefault
value (which raises aKeyError
if not specified).
my_dict = {"apple": 2, "banana": 4, "orange": 1} print(my_dict.pop("apple")) # Output: 2 print(my_dict.pop("mango", "No such fruit exists!")) # Output: "No such fruit exists!"
popitem()
: Removes and returns an arbitrary key-value pair from the dictionary. If the dictionary is empty, it raises aKeyError
.
my_dict = {"apple": 2, "banana": 4, "orange": 1} print(my_dict.popitem()) # Output: ('orange', 1) print(my_dict) # Output: {"apple": 2, "banana": 4}
setdefault(key[, default])
: Returns the value for the given key. If the key is not found, it inserts the key with thedefault
value (which isNone
by default) and returns thedefault
value.
my_dict = {"apple": 2, "banana": 4, "orange":