Dictionaries in Python

Mannan Ul Haq
0

In Python, a dictionary is a mutable and dynamic data structure used to store a collection of key-value pairs. Dictionaries are denoted by enclosing comma-separated key-value pairs in curly braces '{}'. Each key is separated from its value by a colon ':'.


Key properties of Python dictionaries are:

1. Key-Value Pairs: Each item in a dictionary is a pair of a unique key and a value associated with that key. You can access the value by referring to its key.

2. Ordered: Dictionaries in Python are now ordered collections. Since Python 3.7, the insertion order of items is maintained, meaning items are returned in the order they were added to the dictionary.

3. Allows Duplicate Values: While keys in a dictionary must be unique, values can be duplicated. Duplicate values will overwrite existing values.

4. Mutable: Dictionaries in Python are mutable, which means their elements (key-value pairs) can be modified after creation.



Creating Dictionaries:

To create a dictionary in Python, you simply enclose the key-value pairs you want to include within curly braces '{}', separated by commas.


# Example of creating dictionaries
personal_info = {"name": "Alice", "age": 25, "city": "New York"}
grades = {"Math": "A", "Physics": "B", "History": "A"}
mixed = {1: "Alice", "two": [1, 2, 3], (3, 4): "tuple key"}
empty_dict = {}  # An empty dictionary


Using dict() Constructor:

You can also create a dictionary in Python using the 'dict()' constructor.


newdict = dict(name = "Alice", age = 25, country = "England")
print(newdict)  # Outputs: {'name': 'Alice', 'age': 25, 'country': 'England'}


In this case, the arguments to 'dict()' are a series of keyword arguments where the argument names are treated as the dictionary keys and the argument values are the dictionary values.

You can also create a dictionary from an existing iterable object such as a list of tuples, where each tuple is a key-value pair.


# Using dict() constructor
grades = dict([("Math", "A"), ("Physics", "B"), ("History", "A")])
print(grades)  # Outputs: {'Math': 'A', 'Physics': 'B', 'History': 'A'}



Dictionary Length:

In Python, the `len()` function is used to get the number of items (key-value-pairs) in a dictionary.


Here is an example:


personal_info = {"name": "Alice", "age": 25, "city": "New York", "job": "Engineer"}
length = len(personal_info)
print(length)  # Outputs: 4



Access Items:

In Python, you can access items in a dictionary in various ways:


1. Access by Key (Square Brackets): You can access an item in a dictionary by referring to its key inside square brackets `[]`. If the key does not exist, Python raises a `KeyError`.


personal_info = { "name": "Alice", "age" : 25, "city" : "New York" }
print(personal_info["name"])  # Outputs: 'Alice'


2. Access by Key (`get()` method): Alternatively, you can use the `get()` method, which returns the value for a key if it exists in the dictionary. If the key does not exist, it returns `None`, unless a default value is provided.


print(personal_info.get("name"))  # Outputs : 'Alice'
print(personal_info.get("job"))  # Outputs : None


3. Access All Keys (`keys()` method): The `keys()` method returns a view object that contains the keys of the dictionary.


keys = personal_info.keys()
print(keys)  # Outputs: dict_keys(['name', 'age', 'city'])


4. Access All Values (`values()` method): The `values()` method returns a view object that contains the values of the dictionary.


values = personal_info.values()
print(values)  # Outputs: dict_values(['Alice', 25, 'New York'])


5. Access All Key-Value Pairs (`items()` method): The `items()` method returns a view object that contains the key-value pairs of the dictionary.


items = personal_info.items()
print(items)  # Outputs: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])



Check Items:

In Python, you can check if a key exists in a dictionary by using the 'in' keyword. The 'in' keyword checks if a specified key is present in the dictionary and returns 'True' if the key is found in the dictionary, else it returns 'False'.

Here's an example:

personal_info = {"name": "Alice", "age": 25, "city": "New York"}

# Check if a key exists
if "name" in personal_info:
    print("Yes, 'name' is one of the keys in the personal_info dictionary")  # This will be printed

if "job" in personal_info:
    print("Yes, 'job' is one of the keys in the personal_info dictionary")  # This will not be printed

Similarly, you can check if a certain value exists in the dictionary. However, as there is no direct method to do so, you have to use the 'values()' method to get all values and then use the in keyword:

# Check if a value exists
if "Alice" in personal_info.values() :
    print("Yes, 'Alice' is one of the values in the personal_info dictionary")  # This will be printed

if "Engineer" in personal_info.values() :
    print("Yes, 'Engineer' is one of the values in the personal_info dictionary")  # This will not be printed


Modify Items:

In Python, you can modify an item in a dictionary by referring to its key. As dictionaries are mutable, their values can be changed even after the dictionary is created.

Here's an example:

personal_info = {"name": "Alice", "age": 25, "city": "New York"}

# Change an existing item
personal_info["city"] = "Boston"
print(personal_info)  # Outputs: {'name': 'Alice', 'age': 25, 'city': 'Boston'}

In Python, you can update a dictionary by adding a new item or changing an existing item using the 'update()' method. The 'update()' method takes a dictionary as an argument and adds the key-value pairs from this dictionary to the existing dictionary. If a key already exists in the original dictionary, the 'update()' method replaces the old value with the new one from the provided dictionary. Here's an example:

# Updating an existing dictionary
personal_info = {"name": "Alice", "age": 25, "city": "New York"}
additional_info = {"city": "Boston", "job": "Engineer"}

personal_info.update(additional_info)
print(personal_info)  
# Outputs: {'name': 'Alice', 'age': 25, 'city': 'Boston', 'job': 'Engineer'}


Add Items:

Adding new items is similar to modifying items. If you assign a value to a key that doesn’t exist in the dictionary, Python will create a new key-value pair:

personal_info = { "name": "Alice", "age" : 25, "city" : "New York" }

# Add a new item
personal_info["job"] = "Engineer"
print(personal_info)  # Outputs: {'name': 'Alice', 'age' : 25, 'city' : 'New York', 'job' : 'Engineer'}


Copy Dictionary:

In Python, you can create a copy of a dictionary using the 'copy()' method. This method returns a copy of the dictionary.

Here's a simple example:

original_dict = {"key1": "value1", "key2": "value2"}

# Create a copy of the dictionary
copy_dict = original_dict.copy()

print(copy_dict)  # Output: {'key1': 'value1', 'key2': 'value2'}

It's important to note that the 'copy()' method performs a shallow copy of the dictionary, which means it copies the dictionary's keys and values, but doesn't create copies of the values themselves if they're mutable objects. If you modify a mutable object like a list or a dictionary that's a value in the original dictionary, it will also be modified in the copied dictionary.

If you need a deep copy, which is a new dictionary with copies of the values themselves, you can use the 'deepcopy()' function from the 'copy' module:

import copy

original_dict = {"key1": ["value1", "value2"], "key2": {"inner_key": "value"}}

# Create a deep copy of the dictionary
deep_copy_dict = copy.deepcopy(original_dict)

# Now, if you modify a mutable value in the original dictionary, it won't affect the copied dictionary.
original_dict["key1"].append("value3")

print(original_dict)  # Output: {'key1': ['value1', 'value2', 'value3'], 'key2': {'inner_key': 'value'}}
print(deep_copy_dict)  # Output: {'key1': ['value1', 'value2'], 'key2': {'inner_key': 'value'}}


Remove Items:

Python provides several methods and operations to remove items from a dictionary. Here's how you can use each of them:

1. 'pop(key)': This method removes and returns an item from a dictionary having the given key. If the key is not found, it raises a 'KeyError'.

dict1 = {"name": "Alice", "age": 25}
age = dict1.pop("age")
print(age)  # Output: 25
print(dict1)  # Output: {'name': 'Alice'}


2. 'popitem()': This method removes and returns the last inserted item as a pair (key, value). If the dictionary is empty, calling 'popitem()' raises a 'KeyError'.

dict1 = {"name": "Alice", "age": 25}
item = dict1.popitem()
print(item)  # Output: ('age', 25)
print(dict1)  # Output: {'name': 'Alice'}


3. 'clear()': This method removes all items from the dictionary.

dict1 = {"name": "Alice", "age": 25}
dict1.clear()
print(dict1)  # Output: {}


4. 'del': This keyword in Python is used to delete an item with a specified key or the entire dictionary.

dict1 = {"name": "Alice", "age": 25}
del dict1["name"]
print(dict1)  # Output: {'age': 25}

dict1 = {"name": "Alice", "age": 25}
del dict1
print(dict1)  # This will raise a NameError because dict1 no longer exists

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !