Dictionaries - 3.2.6

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 :.

Dictionaries in Python

# Example of a Dictionary in Python

# Creating a dictionary to store information about a student
student_info = {
    "name": "Thomas bao",
    "age": 17,
    "major": "Computer Science",
    "is_enrolled": True
}

# Accessing values
print("Student Name:", student_info["name"])  # Output: Thomas bao
print("Student Age:", student_info["age"])    # Output: 17

# Updating a value
student_info["age"] = 18  # Update the age
print("Updated Age:", student_info["age"])    # Output: 18

# Adding a new key-value pair
student_info["gpa"] = 4.1
print("GPA:", student_info["gpa"])  # Output: 4.1

# 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: Thomas bao
Student Age: 17
Updated Age: 18
GPA: 4.1
Is Enrolled: False

Student Information:
name: Thomas bao
age: 18
major: Computer Science
gpa: 4.1

Javascript Version

%%html
// Example of an Object in JavaScript

// Creating an object to store information about a student
const studentInfo = {
    name: "Collin Ge",
    age: 16,
    major: "Machanical engineer",
    isEnrolled: true
};

// Accessing values
console.log("Student Name:", studentInfo.name);  // Output: Collin Ge
console.log("Student Age:", studentInfo.age);    // Output: 16

// Updating a value
studentInfo.age = 17;  // Update the age
console.log("Updated Age:", studentInfo.age);    // Output: 17

// Adding a new key-value pair
studentInfo.gpa = 4.2;
console.log("GPA:", studentInfo.gpa);  // Output: 4.2

// 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]}`);
    }
}

// Example of an Object in JavaScript

// Creating an object to store information about a student const studentInfo = { name: “Collin Ge”, age: 16, major: “Machanical engineer”, isEnrolled: true };

// Accessing values console.log(“Student Name:”, studentInfo.name); // Output: Collin Ge console.log(“Student Age:”, studentInfo.age); // Output: 16

// Updating a value studentInfo.age = 17; // Update the age console.log(“Updated Age:”, studentInfo.age); // Output: 17

// Adding a new key-value pair studentInfo.gpa = 4.2; console.log(“GPA:”, studentInfo.gpa); // Output: 4.2

// 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]}); } }