Dictionaries are unordered collections of data and are represented with curly brackets { } . Like lists, dictionaries are mutable(changeable) and indexed. With dictionaries, data is stored in a key:value format.
Syntax
myCar= {"Brand": "Hyundai","Model": "Palisade","Year": 2020}
In this example, myCar is the variable that we have assigned our dictionary to.
"Brand", "Model" and "Year" are the keys, while "Hyundai", "Palisade" and "2020" are the values.
You can also type the dictionary out like this.
myCar = { "Brand": "Hyundai", "Model": "Palisade", "Year": 2020 }
Example
You can access the values of a dictionary by referring to its key name inside square brackets:
Syntax
myCar= {"Brand": "Hyundai","Model": "Palisade","Year": 2020} print(myCar["Model"])
Example
You can add new key:value pairs using the following method.
Syntax
myCar= {"Brand": "Hyundai","Model": "Palisade","Year": 2020} myCar["Color"] = "Wine Red" print(myCar)
Example
You can change the value of a specific item by referring to its key .
Syntax
myCar= {"Brand": "Hyundai","Model": "Palisade","Year": 2020} myCar["Model"] = "Genesis" print(myCar)
Example
We can remove an element using the pop method by referring to its key .
Syntax
myCar= {"Brand": "Hyundai","Model": "Palisade","Year": 2020} myCar.pop("Model" print(myCar)
Example
1. Create a new dictionary database called myClass
as an empty dictionary. Add the following key-value pairs:
Keys | Values | Types |
---|---|---|
"Instructor" | "Anna" | String |
"Assistants" | ["Ted", "Nat", "Wei Meng"] | List |
"Students" | 20 | Int |
2. Add a fourth assistant to your database, named Mark
3. Someone from another class has joined this class. add the students count by 1
4. Print out everything you know about your database.
Expected Output:
{"Instructor": "Anna", "Assistants": ["Ted", "Nat", "Wei Meng", "Mark"], "Students": 21 }
You are expected to comply with University policies and guidelines namely, Appropriate Use of Information Resources Policy, IT Usage Policy and Social Media Policy. Users will be personally liable for any infringement of Copyright and Licensing laws. Unless otherwise stated, all guide content is licensed by CC BY-NC 4.0.