π
List and Dictionary in Python
What is a List?
A list in Python is an ordered collection of elements. Lists are mutable, meaning their elements can be changed after the list is created. Lists can contain elements of different data types, including integers, strings, and even other lists.
Examples of Lists
numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'cherry']
mixed = [1, 'hello', 3.14, True]
nested = [[1, 2], [3, 4], [5, 6]]
empty = []
What is a Dictionary?
A dictionary in Python is an unordered collection of key-value pairs. Each key in a dictionary is unique and is used to access its corresponding value. Dictionaries are mutable, meaning their contents can be changed after creation.
Examples of Dictionaries
student_ages = {'Alice': 24, 'Bob': 22, 'Charlie': 23}
capitals = {'France': 'Paris', 'Japan': 'Tokyo', 'India': 'New Delhi'}
mixed_dict = {'name': 'John', 'age': 30, 'is_student': False}
nested_dict = {'numbers': [1, 2, 3], 'letters': ['a', 'b', 'c']}
empty_dict = {}
Difference Between List and Dictionary
While both lists and dictionaries are used to store collections of data, they have some key differences:
- Order: Lists maintain the order of their elements, while dictionaries do not.
- Access: Elements in a list are accessed by their index, while elements in a dictionary are accessed by their key.
- Mutability: Both lists and dictionaries are mutable, but the way they are modified differs.
- Structure: Lists are simple sequences of elements, while dictionaries are collections of key-value pairs.
Indexed Collection
An indexed collection is a data structure where each element can be accessed using an index. In Python, lists are indexed collections because you can access each element by its position in the list, starting from index 0.
Iteration of Dictionary
Iterating over a dictionary involves going through each key-value pair in the dictionary. This can be done using a for loop. Here are some common methods to iterate over a dictionary:
- Using a for loop:
for key in dictionary:
- Using .items() method:
for key, value in dictionary.items():
- Using .keys() method:
for key in dictionary.keys():
- Using .values() method:
for value in dictionary.values():
What is a Key and Value?
In a dictionary, a key is a unique identifier used to access a corresponding value. The value is the data associated with the key. Keys must be immutable types (like strings, numbers, or tuples), while values can be of any data type.
How Key is Used to Find Value
To find a value in a dictionary, you use its key. When you provide the key, the dictionary uses a hashing function to quickly locate the corresponding value. Here's an example:
student_ages = {'Alice': 24, 'Bob': 22, 'Charlie': 23}
age_of_alice = student_ages['Alice'] # This will return 24
In this example, the key 'Alice' is used to find the value 24 in the student_ages
dictionary.
GA:
Comments
Post a Comment