Dictionaries help you store pairs of related information, like names and phone numbers, so you can find things quickly.
Dictionary creation in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
my_dict = {key1: value1, key2: value2, key3: value3}Keys must be unique and usually are strings or numbers.
Values can be any type: numbers, strings, lists, or even other dictionaries.
Examples
Python
empty_dict = {}Python
person = {"name": "Alice", "age": 30, "city": "New York"}Python
scores = {"math": 90, "science": 85, "english": 88}Sample Program
This program creates a dictionary to store a student's name, age, and courses. It then prints each piece of information.
Python
student = {
"name": "John",
"age": 20,
"courses": ["Math", "History", "Science"]
}
print(f"Name: {student['name']}")
print(f"Age: {student['age']}")
print(f"Courses: {', '.join(student['courses'])}")Important Notes
You can create dictionaries using the {} syntax or the dict() function.
Keys must be immutable types like strings, numbers, or tuples.
Dictionaries do not keep order before Python 3.7, but from 3.7+ they remember the order items were added.
Summary
Dictionaries store data as key-value pairs for easy lookup.
Keys are unique and values can be any type.
Use curly braces {} to create dictionaries quickly.
Practice
1. Which of the following is the correct way to create an empty dictionary in Python?
easy
Solution
Step 1: Understand dictionary syntax
Dictionaries in Python are created using curly braces{}.Step 2: Identify the empty dictionary
An empty dictionary is represented as{}, not square brackets, parentheses, or quotes.Final Answer:
my_dict = {} -> Option CQuick Check:
Empty dictionary = {} [OK]
Hint: Use curly braces {} for dictionaries, brackets [] for lists [OK]
Common Mistakes:
- Using [] which creates a list, not a dictionary
- Using () which creates a tuple, not a dictionary
- Using '' which creates an empty string
2. Which of the following is the correct syntax to create a dictionary with keys 'a' and 'b' and values 1 and 2 respectively?
easy
Solution
Step 1: Check dictionary key-value pair syntax
Dictionary pairs use colon:between key and value inside curly braces.Step 2: Identify correct syntax
my_dict = {'a':1, 'b':2} uses curly braces and colons correctly. Options A and C use wrong brackets, and D uses equals sign which is invalid.Final Answer:
my_dict = {'a':1, 'b':2} -> Option DQuick Check:
Dictionary pairs use : inside {} [OK]
Hint: Use colons : between keys and values inside {} [OK]
Common Mistakes:
- Using square brackets [] instead of curly braces {}
- Using parentheses () instead of curly braces {}
- Using equals sign = instead of colon :
3. What will be the output of the following code?
my_dict = {1: 'one', 2: 'two', 3: 'three'}
print(my_dict[2])medium
Solution
Step 1: Understand dictionary key lookup
Accessingmy_dict[2]retrieves the value for key 2.Step 2: Find value for key 2
Key 2 maps to the string 'two' in the dictionary.Final Answer:
'two' -> Option AQuick Check:
my_dict[2] = 'two' [OK]
Hint: Dictionary[key] returns the value for that key [OK]
Common Mistakes:
- Confusing keys and values
- Expecting the key itself as output
- Mistaking KeyError when key exists
4. The following code throws an error. What is the problem?
my_dict = {1: 'one', 2: 'two', 3: 'three'}
print(my_dict[4])medium
Solution
Step 1: Check dictionary keys
The dictionary has keys 1, 2, and 3 only.Step 2: Accessing a missing key
Trying to accessmy_dict[4]causes a KeyError because key 4 is not present.Final Answer:
Key 4 does not exist in the dictionary -> Option AQuick Check:
Accessing missing key causes KeyError [OK]
Hint: Check if key exists before accessing dictionary [OK]
Common Mistakes:
- Assuming all keys exist
- Confusing syntax error with runtime error
- Thinking keys must be strings
5. You want to create a dictionary from two lists:
keys = ['name', 'age', 'city'] and values = ['Alice', 30, 'NY']. Which code correctly creates this dictionary?hard
Solution
Step 1: Understand dictionary creation from two lists
We need to pair each key with its corresponding value by index.Step 2: Analyze options
my_dict = {keys[i]: values[i] for i in range(len(keys))} uses dictionary comprehension with index to pair keys and values correctly. my_dict = dict(keys, values) is invalid syntax. my_dict = {keys: values} creates a dictionary with one key (the list) which is invalid. my_dict = dict(zip(values, keys)) reverses keys and values.Final Answer:
my_dict = {keys[i]: values[i] for i in range(len(keys))} -> Option BQuick Check:
Use dict comprehension with index to pair keys and values [OK]
Hint: Use dict comprehension with index or zip() to pair keys and values [OK]
Common Mistakes:
- Using dict() with two lists directly
- Swapping keys and values in zip()
- Using list as a key
