Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

PYTHON DICTIONARIES

In Python, a dictionary is a built-in data type that represents a collection of key-value pairs. It is also known as an associative array or a hash map in other programming languages. Dictionaries are mutable, unordered, and can contain any data type as values. However, keys must be immutable objects such as strings, numbers, or tuples.

Characteristics of Dictionaries:
1. Mutable:
– Dictionaries can be modified after creation. You can add, modify, or remove key-value pairs.

2. Unordered:
– Dictionaries do not maintain the order of key-value pairs as they are added.
– Therefore, dictionaries do not support indexing or slicing.

3. Key-Value Pairs:
– Each element in a dictionary consists of a key-value pair.
– The key is used to access the corresponding value in the dictionary.

Creating Dictionaries:
– Dictionaries are defined using curly braces `{}`.
– Key-value pairs are separated by commas, with the key and value separated by a colon `:`.

Here are some code examples illustrating the characteristics of dictionaries in Python:

1. Mutable:

“`python
# Creating a dictionary
person = {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}

# Modifying a value in the dictionary
person[‘age’] = 35

print(person) # Output: {‘name’: ‘John’, ‘age’: 35, ‘city’: ‘New York’}
“`

2. Unordered:

“`python
# Creating a dictionary
person = {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}

# Printing the dictionary
print(person) # Output: {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
“`

The output may not always appear in the same order as the elements were defined.

3. Key-Value Pairs:

“`python
# Creating a dictionary
person = {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}

# Accessing values using keys
print(person[‘name’]) # Output: John
print(person[‘age’]) # Output: 30
print(person[‘city’]) # Output: New York
“`

Dictionaries consist of key-value pairs, where each key is associated with a corresponding value. Keys are used to access values in the dictionary.

These examples demonstrate how dictionaries work in Python and illustrate their key characteristics.

 

Example:
“`python
my_dict = {“name”: “John”, “age”: 30, “city”: “New York”}
“`

Accessing Elements:

Navigating a Python dictionary involves accessing, modifying, adding, and removing key-value pairs. Here are some common operations to navigate a dictionary:

1. Accessing Values:
Use keys to access corresponding values in the dictionary.

“`python
person = {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
print(person[‘name’]) # Output: John
print(person[‘age’]) # Output: 30
“`

2. Modifying Values:
Modify the value associated with a key in the dictionary.

“`python
person = {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
person[‘age’] = 35
print(person) # Output: {‘name’: ‘John’, ‘age’: 35, ‘city’: ‘New York’}
“`

3. Adding New Key-Value Pairs:
Add new key-value pairs to the dictionary.

“`python
person = {‘name’: ‘John’, ‘age’: 30}
person[‘city’] = ‘New York’
print(person) # Output: {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
“`

4. Removing Key-Value Pairs:
Use the `del` keyword or the `pop()` method to remove key-value pairs.

“`python
person = {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
del person[‘age’]
print(person) # Output: {‘name’: ‘John’, ‘city’: ‘New York’}
“`

5. Iterating Over Keys and Values:
Use loops to iterate over keys, values, or key-value pairs in a dictionary.

“`python
person = {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
for key in person:
print(key, person[key])

# Output:
# name John
# age 30
# city New York
“`

These operations allow you to effectively navigate and manipulate dictionaries in Python.

 

 

Adding and Modifying Elements:
– You can add new key-value pairs to a dictionary by assigning a value to a new key.
– If the key already exists in the dictionary, assigning a new value to the key will update the existing value.

Example:
“`python
my_dict[“email”] = “john@example.com”
my_dict[“age”] = 35
“`

Removing Elements:
– You can remove key-value pairs from a dictionary using the `del` keyword or the `pop()` method.
– The `del` keyword removes a specific key-value pair, while the `pop()` method removes the key-value pair associated with the specified key and returns its value.

Example:
“`python
del my_dict[“city”]
removed_age = my_dict.pop(“age”)
“`

Dictionary Methods:
– Dictionaries support various built-in methods for common operations such as accessing keys, values, and key-value pairs.

Example:
“`python
keys = my_dict.keys()
values = my_dict.values()
items = my_dict.items()
“`

Use Cases:
– Dictionaries are commonly used to represent structured data, such as user profiles, configurations, and mappings.
– They are useful for storing and accessing data in a flexible and efficient manner.

Dictionaries provide a powerful and flexible way to work with key-value pairs in Python. Their ability to store and retrieve data based on keys makes them valuable for a wide range of programming tasks.

SOME COMMONLY USED INBUILT FUNCTIONS IN PYTHON DICTIONARIES

Below are some commonly used built-in functions and methods for dictionaries in Python:

1. `len()`:
– Returns the number of key-value pairs in the dictionary.

“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
print(len(my_dict)) # Output: 3
“`

2. `keys()`:
– Returns a view object that displays a list of all the keys in the dictionary.

“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
print(my_dict.keys()) # Output: dict_keys([‘a’, ‘b’, ‘c’])
“`

3. `values()`:
– Returns a view object that displays a list of all the values in the dictionary.

“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
print(my_dict.values()) # Output: dict_values([1, 2, 3])
“`

4. `items()`:
– Returns a view object that displays a list of key-value tuple pairs in the dictionary.

“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
print(my_dict.items()) # Output: dict_items([(‘a’, 1), (‘b’, 2), (‘c’, 3)])
“`

5. `get()`:
– Returns the value of the specified key. If the key does not exist, it returns the specified default value (None by default).

“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
print(my_dict.get(‘a’)) # Output: 1
print(my_dict.get(‘d’, 0)) # Output: 0 (default value)
“`

6. `pop()`:
– Removes the item with the specified key and returns its value.

“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
print(my_dict.pop(‘b’)) # Output: 2
print(my_dict) # Output: {‘a’: 1, ‘c’: 3}
“`

7. `popitem()`:
– Removes the last inserted key-value pair from the dictionary and returns it as a tuple.

“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
print(my_dict.popitem()) # Output: (‘c’, 3)
print(my_dict) # Output: {‘a’: 1, ‘b’: 2}
“`
Sure, here are some more built-in functions and methods for dictionaries in Python:

8. `clear()`:
– Removes all the elements from the dictionary.

“`python
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
my_dict.clear()
print(my_dict) # Output: {}
“`

9. `update()`:
– Updates the dictionary with elements from another dictionary or from an iterable of key-value pairs.

“`python
my_dict = {‘a’: 1, ‘b’: 2}
my_dict.update({‘b’: 3, ‘c’: 4})
print(my_dict) # Output: {‘a’: 1, ‘b’: 3, ‘c’: 4}
“`

10. `setdefault()`:
– Returns the value of the specified key. If the key does not exist, inserts the key with the specified default value.

“`python
my_dict = {‘a’: 1, ‘b’: 2}
print(my_dict.setdefault(‘b’, 3)) # Output: 2
print(my_dict.setdefault(‘c’, 4)) # Output: 4
print(my_dict) # Output: {‘a’: 1, ‘b’: 2, ‘c’: 4}
“`

11. `copy()`:
– Returns a shallow copy of the dictionary.

“`python
my_dict = {‘a’: 1, ‘b’: 2}
new_dict = my_dict.copy()
print(new_dict) # Output: {‘a’: 1, ‘b’: 2}
“`

12. `fromkeys()`:
– Returns a new dictionary with the specified keys and the specified value for each key.

“`python
keys = [‘a’, ‘b’, ‘c’]
value = 0
my_dict = dict.fromkeys(keys, value)
print(my_dict) # Output: {‘a’: 0, ‘b’: 0, ‘c’: 0}
“`

These functions and methods provide convenient ways to work with dictionaries in Python.

 

 

Join the conversation