Fall 2024 - P4
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.2 Dictionaries
Dictionaries in Python
Dictionaries are a built-in data type in Python that allows you to store collections of key-value pairs. They are also known as associative arrays or hash maps in other programming languages.
Key Features
- Unordered: Dictionaries do not maintain the order of the elements. However, as of Python 3.7, they preserve insertion order.
- Mutable: You can change, add, or remove elements after the dictionary is created.
- Indexed by keys: Each value is accessed via its unique key rather than an index.
Syntax
A dictionary is created by placing a comma-separated sequence of key-value pairs within curly braces {}
. Each key is separated from its value by a colon :
.
# Example of a Dictionary in Python
# Creating a dictionary to store information about a student
student_info = {
"name": "John Doe",
"age": 20,
"major": "Computer Science",
"is_enrolled": True
}
# Accessing values
print("Student Name:", student_info["name"]) # Output: John Doe
print("Student Age:", student_info["age"]) # Output: 20
# Updating a value
student_info["age"] = 21 # Update the age
print("Updated Age:", student_info["age"]) # Output: 21
# Adding a new key-value pair
student_info["gpa"] = 3.5
print("GPA:", student_info["gpa"]) # Output: 3.5
# Removing a key-value pair
del student_info["is_enrolled"]
print("Is Enrolled:", "is_enrolled" in student_info) # Output: False
# Looping through the dictionary
print("\nStudent Information:")
for key, value in student_info.items():
print(f"{key}: {value}")
Student Name: John Doe
Student Age: 20
Updated Age: 21
GPA: 3.5
Is Enrolled: False
Student Information:
name: John Doe
age: 21
major: Computer Science
gpa: 3.5
Javascript Version
%%js
// Example of an Object in JavaScript
// Creating an object to store information about a student
const studentInfo = {
name: "John Doe",
age: 20,
major: "Computer Science",
isEnrolled: true
};
// Accessing values
console.log("Student Name:", studentInfo.name); // Output: John Doe
console.log("Student Age:", studentInfo.age); // Output: 20
// Updating a value
studentInfo.age = 21; // Update the age
console.log("Updated Age:", studentInfo.age); // Output: 21
// Adding a new key-value pair
studentInfo.gpa = 3.5;
console.log("GPA:", studentInfo.gpa); // Output: 3.5
// Removing a key-value pair
delete studentInfo.isEnrolled;
console.log("Is Enrolled:", studentInfo.isEnrolled === undefined); // Output: true
// Looping through the object
console.log("\nStudent Information:");
for (const key in studentInfo) {
if (studentInfo.hasOwnProperty(key)) {
console.log(`${key}: ${studentInfo[key]}`);
}
}
<IPython.core.display.Javascript object>