Python Practice › Dictionary Programs › Program 5
Odd and even keys
Write a Python program to get lists of the items with even keys and with odd keys.
Input
{1: 25, 5: "abc", 8: "pqr", 21: "xyz", 12: "def", 2: "utv"}Output
Even Key = [[8, 'pqr'], [12, 'def'], [2, 'utv']] Odd Key = [[1, 25], [5, 'abc'], [21, 'xyz']]
Approach
- Filter
items()bykey % 2.
Solution
d = {1: 25, 5: "abc", 8: "pqr", 21: "xyz", 12: "def", 2: "utv"}even = [[k, v] for k, v in d.items() if k % 2 == 0]odd = [[k, v] for k, v in d.items() if k % 2 == 1]print("Even Key =", even)print("Odd Key =", odd)Output
Even Key = [[8, 'pqr'], [12, 'def'], [2, 'utv']] Odd Key = [[1, 25], [5, 'abc'], [21, 'xyz']]
Learn the concept
New to this topic? Read the lesson, then come back.