python - 字典的平方值

标签 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}

我要:

 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}

我试过:

 dict1_squared = dict**2.

 dict1_squared = pow(dict,2.)

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

我的尝试没有任何成功。

最佳答案

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

for d in dict1.values():
    for k in d:
        d[k] **= 2

关于python - 字典的平方值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39067114/

相关文章:

python - 使用类字典映射到 Python 中的实例方法

ios - 如何在 swift 中打印字典值数组

c++ - 另一个奇怪的编译器错误 : calling a templated function which gives undefined referenes

python - 从字典值创建词云

python - 如何使用elasticsearch-dsl查找数组中所有索引中的不同值?

python - django密码重置NoReverseMatch错误

python - LeakyReLU 中的 "negative"斜率在哪里?

python - 如何将输入传递给 Keras 中的 2D Conv?

python - 从嵌套字典中删除空字符串键,字典理解

python - 正则表达式解析字符串中的百分比