Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Squaring values of dictionary

I am using Python 2.7, still learning about dictionaries. I am focusing on performing numerical computations for dictionaries and need some help.

I have a dictionary and I would like to square the values in it:

 dict1 = {'dog': {'shepherd': 5,'collie': 15,'poodle': 3,'terrier': 20},
'cat': {'siamese': 3,'persian': 2,'dsh': 16,'dls': 16},
'bird': {'budgie': 20,'finch': 35,'cockatoo': 1,'parrot': 2}

I want:

 dict1 = {'dog': {'shepherd': 25,'collie': 225,'poodle': 9,'terrier': 400},
'cat': {'siamese': 9,'persian': 4,'dsh': 256,'dls': 256},
'bird': {'budgie': 400,'finch': 1225,'cockatoo': 1,'parrot': 4}

I tried:

 dict1_squared = dict**2.

 dict1_squared = pow(dict,2.)

 dict1_squared = {key: pow(value,2.) for key, value in dict1.items()}

I did not have any success with my attempts.

like image 932
Caroline.py Avatar asked Sep 19 '25 01:09

Caroline.py


1 Answers

It's because you have nested dictionaries, look:

results = {}

for key, data_dict in dict1.iteritems():
    results[key] = {key: pow(value,2.) for key, value in data_dict.iteritems()}
like image 163
loleknwn Avatar answered Sep 21 '25 14:09

loleknwn