Explanation:
1. Dictionary Creation
d = {'apple': 2, 'banana': 3, 'cherry': 4}
Creates a dictionary d with keys as fruit names and values as numbers.
Example content:
'apple': 2
'banana': 3
'cherry': 4
2. Initialize Counter
count = 0
Initializes a variable count to store the running total.
Starts at 0.
3. Loop Over Dictionary Items
for k, v in d.items():
Loops over each key-value pair in the dictionary.
k = key (fruit name), v = value (number).
.items() gives pairs: ('apple', 2), ('banana', 3), ('cherry', 4).
4. Check for Letter 'a' in Key
if 'a' in k:
Checks if the key contains the letter 'a'.
Only keys with 'a' are processed.
'apple' → True, 'banana' → True, 'cherry' → False.
5. Add Value to Counter
count += v
Adds the value v to count if the key has 'a'.
Step by step:
'apple': count = 0 + 2 → 2
'banana': count = 2 + 3 → 5
'cherry': skipped
6. Print Final Count
print(count)
Prints the final total of values where keys contain 'a'.
Output:
5


0 Comments:
Post a Comment