- 1 year ago 87
Python Question

Performing Power Operations in Dictionaries

dict1 = {'A': 2,'B': 4,'C': 6}

I want a new dictionary to be the values of dict1 squared.

dict2 = {'A': 4,'B': 16,'C': 36}

A tried using

for k in dict1.keys():
value = dict[k]
for k1 in value.keys():
value[k1] = value**2 # also tried pow(value,2.)

The error I get is AttributeError: 'float' object has no attribute 'keys'. Any ideas what I am doing wrong?

Answer Source

You first need to create dict2:

dict2 = {}

Then, you can populate it using the keys and values of dict1:

for key in dict1.keys():
    dict2[key] = dict1[key] ** 2

Or in one line:

dict2 = {key: value ** 2 for key, value in dict1.items()}