- 1 year ago 81
Python Question

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.

Answer Source

You were very close with the dictionary comprehension. The issue is that value in your solution is a dictionary itself, so you have to iterate over it too.

dict1_squared = {key: {k: pow(v,2) for k,v in value.items()} for key, value in dict1.items()}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download