Square of every value

Square of every value

EasyDictionary Programs · 2 of 94

Write a Python program to print the square of every value in a dictionary.

Input
{"a": 5, "b": 3, "c": 6, "d": 8}
Output
a : 25
b : 9
c : 36
d : 64

Approach

  1. Loop over items().

Solution

Python
d = {"a": 5, "b": 3, "c": 6, "d": 8}for key, value in d.items():    print(key, ":", value ** 2)
Output
a : 25
b : 9
c : 36
d : 64

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Add elements to a dictionary

Add elements to a dictionary

EasyDictionary Programs · 1 of 94

Write a Python program to add elements to a dictionary.

Input
{"name": "Asha"}
Output
{'name': 'Asha', 'city': 'Pune', 'age': 29, 'role': 'tester'}

Approach

  1. Assign to a new key, or use update() for several keys.

Solution

Python
person = {"name": "Asha"}person["city"] = "Pune"person.update({"age": 29, "role": "tester"})print(person)
Output
{'name': 'Asha', 'city': 'Pune', 'age': 29, 'role': 'tester'}

Line by line

Line 2

Assigning to a key that does not exist adds it.

Line 3

update adds (or replaces) several keys at once.

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs

Python Dictionary Programs with Solutions

Python Practice › Dictionary Programs

Python Dictionary Programs with Solutions

94 programs91 easy3 medium0 hard

94 dictionary programs: adding, removing and renaming keys, merging, sorting by key or value, counting with dictionaries, grouping, inverting, and working with nested dictionaries and lists of dictionaries. Every solution is explained with its real output.

Before you start

Read the Dictionaries lesson first if the topic is new to you.

All programs