字典的平方值

Car*_*.py 3 python dictionary

我正在使用Python 2.7,仍在学习字典.我专注于为字典执行数值计算,需要一些帮助.

我有一本字典,我想对其中的值进行平方:

 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}
Run Code Online (Sandbox Code Playgroud)

我想要:

 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}
Run Code Online (Sandbox Code Playgroud)

我试过了:

 dict1_squared = dict**2.

 dict1_squared = pow(dict,2.)

 dict1_squared = {key: pow(value,2.) for key, value in dict1.items()}
Run Code Online (Sandbox Code Playgroud)

我的尝试没有任何成功.

Ste*_*ann 5

其中一个我可能更喜欢循环的情况:

for d in dict1.values():
    for k in d:
        d[k] **= 2
Run Code Online (Sandbox Code Playgroud)