Python 字典的平方值
我正在使用Python2.7,还在学习字典。我专注于为字典执行数值计算,需要一些帮助 我有一本字典,我想将其中的值平方:Python 字典的平方值,python,dictionary,Python,Dictionary,我正在使用Python2.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': 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()}
我的尝试没有成功 这是因为您有嵌套字典,请看:
results = {}
for key, data_dict in dict1.iteritems():
results[key] = {key: pow(value,2.) for key, value in data_dict.iteritems()}
你对词典的理解能力很好。问题在于,解决方案中的值本身就是一个字典,因此您也必须对其进行迭代
dict1_squared = {key: {k: pow(v,2) for k,v in value.items()} for key, value in dict1.items()}
我可能更喜欢循环的一种情况:
for d in dict1.values():
for k in d:
d[k] **= 2
根据你的问题,我认为完成一个教程是个好主意。你说你想把字典弄平,但那不是你想做的。您正在尝试在字典中对值进行平方运算。要使字典中的值平方,首先需要获取值。Python的
for
循环可以帮助实现这一点
# just an example
test_dict = {'a': {'aa': 2}, 'b': {'bb': 4}}
# go through every key in the outer dictionary
for key1 in test_dict:
# set a variable equal to the inner dictionary
nested_dict = test_dict[key1]
# get the values you want to square
for key2 in nested_dict:
# square the values
nested_dict[key2] = nested_dict[key2] ** 2
如果您的结构始终相同,您可以这样做:
for k,w in dict1.items():
for k1,w1 in w.items():
print w1, pow(w1,2)
20 400
1 1
2 4
35 1225
5 25
15 225
20 400
3 9
3 9
16 256
2 4
16 256
您必须迭代循环(2层深度)。然后你需要自己计时。