I'm trying to under behaviour of using defalultdict with and without assignments in python
data is as follows :
data = {'APPLaunch_ftrace': [63.3, 24.5, 8.4, 2.3, 0.9, 0.3, 0.2, 0.0], '1080pEncode_ftrace': [22.9, 27.6, 21.3, 16.1, 12.1, 0.0, 0.0, 0.0]}
Please help me understand difference of the following :
d = {}
for k,v in data.iteritems():
for i in range(0,8):
d['cores{0}'.format(i)] = d.setdefault('cores{0}'.format(i),0) + v[i] * 2
print d
{'cores2': 59.400000000000006, 'cores3': 36.800000000000004, 'cores0': 172.39999999999998, 'cores1': 104.2, 'cores6': 0.4, 'cores7': 0.0, 'cores4': 26.0, 'cores5': 0.6}
and following :
d = {}
for k,v in data.iteritems():
for i in range(0,8):
d.setdefault('cores{0}'.format(i), 0) + v[i] *2
126.6
49.0
16.8
4.6
1.8
0.6
0.4
0.0
45.8
55.2
42.6
32.2
24.2
0.0
0.0
0.0
>>> print d
{'cores2': 0, 'cores3': 0, 'cores0': 0, 'cores1': 0, 'cores6': 0, 'cores7': 0, 'cores4': 0, 'cores5': 0}
In first code in line:
d['cores{0}'.format(i)] = d.setdefault('cores{0}'.format(i),0) + v[i] * 2
you real do three jobs
in part d.setdefault('cores{0}'.format(i),0)
you make dict
keys with names and with values 0
.
next you sum this entry's value (0
) with v[i]*2
and last you assign this summation value to d
dict's entry with key
=='cores{0}'.format(i)
this process repeats 8 times for each entry of data
.
But
In second code you have:
d.setdefault('cores{0}'.format(i), 0) + v[i] *2
it is similar to your first code but you dont have assignation part ( part 3 ). you just do part 1 and 2 but not part 3.
so you really do:
in part d.setdefault('cores{0}'.format(i),0)
you make dict
keys with names and with values 0
.
next you sum this entry's value (0
) with v[i]*2
this summation occures but its value doesn't save on d
dict , it is just show on console output and nothing else.