2016-08-21 2 views
3

저는 파이썬 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()} 

내가하지 않았다 내 시도로 성공. 당신이 사전을 중첩 때문에

+1

당신은 루프 (2 단계 깊이)을 반복해야합니다. 그렇다면 스스로 시간을 할애해야합니다. –

답변

3

당신은 사전 이해와 매우 근접했다. 솔루션의 은 사전 자체이므로이 역시 반복해야합니다. 내가 루프를 선호 할 수도하는 경우

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

그것은 봐, :

results = {} 

for key, data_dict in dict1.iteritems(): 
    results[key] = {key: pow(value,2.) for key, value in data_dict.iteritems()} 
5

하나 : 당신의 질문에

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

을 바탕으로 나는 튜토리얼을 통해 일하기 좋은 아이디어라고 생각합니다. Here is one from tutorialspoint. 당신은 사전을 정사각형으로 만들겠다고 말했지만, 그것은 당신이하려고하는 것이 아닙니다. 사전 내에서 값을 제곱하려고합니다. 사전에서 값을 제곱하려면 먼저 값을 가져와야합니다. 파이썬의 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 
0

당신의 구조가이 방법으로 할 수 항상 곁에 동일한 경우 :

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