Trying to access my_dict[4] causes a KeyError because key 4 is not present.
Final Answer:
Key 4 does not exist in the dictionary -> Option A
Quick 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
A. my_dict = {keys: values}
B. my_dict = {keys[i]: values[i] for i in range(len(keys))}
C. my_dict = dict(keys, values)
D. my_dict = dict(zip(values, keys))
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 B
Quick 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]