Odd and even keys

EasyDictionary Programs · 5 of 94

Write a Python program to get lists of the items with even keys and with odd keys.

Advertisement
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

  1. Filter items() by key % 2.

Solution

Python
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.

More dictionary programs

← All 94 Dictionary Programs