Dictionaries
Introduction to Python
Getting Started
Comments
Variables
Data Types
Type Casting
Input and Output
Operators
Strings
Booleans
Conditional Statements
While Loop
For Loop
Loop Control Statements
Lists
Tuples
Sets
Dictionaries
Functions
Function Arguments and Return Values
Variable Scope
Recursion
Lambda Functions
Arrays and Python Lists
Modules
Dates and Math
String Formatting
File Handling
Try and Except
Classes and Objects
Inheritance
Iterators
JSON
RegEx
Dictionaries
Definition: A dictionary is an ordered (as of Python 3.7) and changeable collection of data stored in key-value pairs. Instead of indexing items by numbers, dictionaries look up values using unique keys.
Why: Dictionaries are a core built-in data structure because they allow you to map associations between related pieces of information (like a word and its meaning, or a user and their account profile).
Syntax
dictionary_name = {
"key1": "value1",
"key2": "value2"
}
Example
student = {
"name": "Anu",
"age": 19,
"marks": 88
}
print(student)
print(student["name"])
print(student["marks"])
Explanation
- Curly Brackets & Colons: Dictionaries are defined with curly brackets
{ }, and each key is separated from its value by a colon:. - Keys: In this example,
"name","age", and"marks"are the keys. They act as labels to retrieve data. - Values:
"Anu",19, and88are the values associated with those keys. - Accessing Data: Passing a key in square brackets (e.g.,
student["name"]) retrieves its corresponding value.
Key Notes
- Keys must be unique; you cannot have two identical keys in a single dictionary. If you assign a value to an existing key, the old value gets overwritten.
- Keys are case-sensitive (e.g.,
"Age"and"age"are treated as two different keys). - Values can be of any data type, including strings, integers, booleans, or even lists.
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute