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.
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()}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With