A Python dictionary is a collection of key-value pairs, where each key is
unique. Dictionaries are mutable, which means that elements can be added,
removed, or modified after the dictionary is created. They are also unordered,
which means that elements are not stored in a specific order.
Here is an example of how to create a dictionary in Python:
# Creating an empty dictionary
my_dict = {}
# Creating a dictionary with initial key-value pairs
my_dict = {
'name':
'John',
'age':
25,
'city':
'New York'}
# Creating a dictionary using the dict() constructor
my_dict =
dict(name=
'John', age=
25, city=
'New York')
To access the value of a specific key, you can use the square brackets
notation:
# Accessing the value of a specific key
print(my_dict[
'name'])
# Output: 'John'
You can also use the get() method to access the value of a key, which
returns None if the key is not found:
print(my_dict.get(
'age'))
# Output: 25
print(my_dict.get(
'gender'))
# Output: None
You can add, remove or modify key-value pairs to the dictionary using the
following methods:
# Adding a new key-value pair
my_dict[
'gender'] =
'male'
# Modifying the value of an existing key
my_dict[
'age'] =
30
# Removing a key-value pair
del my_dict[
'city']
# Removing all key-value pairs
my_dict.clear()
You can also use the items()
,
keys()
, and values()
methods to access the items,
keys, and values of the dictionary, respectively:
# Accessing all the items of the dictionary
print(my_dict.items())
# Output: dict_items([('name', 'John'), ('age', 25), ('city', 'New York')])
# Accessing all the keys of the dictionary
print(my_dict.keys())
# Output: dict_keys(['name', 'age', 'city'])
# Accessing all the values of the dictionary
print(my_dict.values())
# Output: dict_values(['John', 25, 'New York'])
You can also use the in
keyword to check if a key is present in the dictionary:
print(
'name'
in my_dict)
# Output: True
print(
'gender'
in my_dict)
# Output: False
Python dictionaries are very powerful data structures and are widely used in
a variety of programming tasks. They are also very efficient in terms of time
complexity, making them a great choice for large data sets.
Amelioration
This
article was researched and written with the help of ChatGPT, a language
model developed by OpenAI."
"Special thanks to ChatGPT for
providing valuable information and examples used in this article."
No comments:
Post a Comment