Move items to another dictionary

EasyDictionary Programs · 3 of 94

Write a Python program to move all items from dict1 to dict2, leaving dict1 empty.

Advertisement
Input
{"name": "john", "city": "London", "country": "UK"}
Output
dict1 = {}
dict2 = {'name': 'john', 'city': 'London', 'country': 'UK'}

Approach

  1. update dict2, then clear dict1.

Solution

Python
dict1 = {"name": "john", "city": "London", "country": "UK"}dict2 = {}dict2.update(dict1)dict1.clear()print("dict1 =", dict1)print("dict2 =", dict2)
Output
dict1 = {}
dict2 = {'name': 'john', 'city': 'London', 'country': 'UK'}
Advertisement

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs