w3resource

Python: Count the values associated with key in a dictionary

Python dictionary: Exercise-26 with Solution

Write a Python program to count the values associated with a key in a dictionary.

Sample Solution:

Python Code:

# Create a list 'student' containing dictionaries, each representing a student with 'id', 'success', and 'name' information.
student = [{'id': 1, 'success': True, 'name': 'Lary'},
 {'id': 2, 'success': False, 'name': 'Rabi'},
 {'id': 3, 'success': True, 'name': 'Alex'}]

# Print the sum of 'id' values for all students in the 'student' list.
print(sum(d['id'] for d in student))

# Print the sum of 'success' values (True/False) for all students in the 'student' list.
print(sum(d['success'] for d in student))
 

Sample Output:

6
2 

Python Code Editor:

Previous: Write a Python program to print a dictionary in table format.
Next: Write a Python program to convert a list into a nested dictionary of keys.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.