Dictionaires
Introduction to Dictionaries in Python
Dictionaries are built-in data structures in Python.
They store data in key/value pairs.
Accessing values is done through keys, not numeric indices as with lists.
What is a Dictionary?
A dictionary is an indexed container.
Elements are indexed by keys rather than positions (0, 1, 2, etc.).
Each entry in a dictionary consists of a pair: a key and a value.
Example of Using a Dictionary
Consider storing student names:
Using a list:
students = ["Paul", "Peng", "Yasmin", "Maria"]Accessing elements requires knowing the index:
To retrieve "Peng":
students[1]gives "Peng".
To retrieve "Maria":
students[3]gives "Maria".
Transition to Dictionaries
A dictionary provides a more efficient approach:
-students = {1: "Paul", 5678: "Peng"}Keys are the student IDs; values are the names.
Add more pairs:
students[9876] = "Yasmin"students[6543] = "Maria".
Accessing Values in a Dictionary
To access "Peng":
Use the key:
students[5678]returns "Peng".
To access "Maria":
Use:
students[6543]returns "Maria".
Dictionary Methods
You can retrieve all keys in a dictionary:
students.keys()returns all keys.
Retrieve all values:
students.values()returns all values.
Characteristics of Dictionaries
The order of elements is not significant; they are indexed by keys, not by position.
Keys must be unique to identify each pair uniquely.
Values can be of any type, including strings, integers, or even lists.
Advanced Usage of Values
Values can be complex data structures:
For example, a string containing grades:
Value could be formatted as: "name;grade1;grade2;..."
This allows the dictionary to function similarly to a small database.
Conclusion
The video covered the dictionaries in Python, highlighting their ability to store data indexed by unique keys in key/value pairs.
A dictionary provides a flexible way to structure data, where both keys and values can be tailored to meet various needs.