Nested dictionary from a list of keys

EasyDictionary Programs · 66 of 94

Write a Python program to nest each item of a dictionary under a key from a list.

Advertisement
Input
{"sqatools": 8, "python": 6}, [1, 2]
Output
{1: {'sqatools': 8}, 2: {'python': 6}}

Approach

  1. zip the list with the dict’s items.

Solution

Python
d = {"sqatools": 8, "python": 6}keys = [1, 2]print({k: {name: v} for k, (name, v) in zip(keys, d.items())})
Output
{1: {'sqatools': 8}, 2: {'python': 6}}
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs