Reputation: 313
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.
Upvotes: 4
Views: 3463
Reputation: 1
square = {i:i**2 for i in range(1,8)}
print(square)
#-- or --#
square2 = {f"Square of {i} is":i**2 for i in range(1,8)}
for k,v in square2.items():
print(f"{k}:{v}")
Upvotes: 0
Reputation: 2169
If your structure is alway the same you can do this way:
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
Upvotes: 0
Reputation: 2516
Based on your question I think it would be a good idea to work through a tutorial. Here is one from tutorialspoint. You said you are trying to square the dictionary, but that is not what you are trying to do. You are trying to square the values within a dictionary. To square the values within the dictionary, you first need to get the values. Python's for
loops can help with this.
# 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
Upvotes: 1
Reputation: 28606
One of those cases where I might prefer loops:
for d in dict1.values():
for k in d:
d[k] **= 2
Upvotes: 4
Reputation: 113
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()}
Upvotes: 4
Reputation: 2378
You were very close with the dictionary comprehension. The issue is that value in your solution is a dictionary itself, so you have to iterate over it too.
dict1_squared = {key: {k: pow(v,2) for k,v in value.items()} for key, value in dict1.items()}
Upvotes: 2