0

I have a dictionary:

adict = {'key1':{'t1':{'thedec':.078, 'theint':1000, 'thechar':100},
                          't2':{'thedec':.0645, 'theint':10, 'thechar':5},
                          't3':{'thedec':.0871, 'theint':250, 'thechar':45},
                          't4':{'thedec':.0842, 'theint':200, 'thechar':37},
                          't5':{'thedec':.054, 'theint':409, 'thechar':82},
                          't6':{'thedec':.055, 'theint':350, 'thechar':60}}}

I use the following loop so that I can pair values of 'theint' in a vector so that ultimately I can easily use perform statistical calculations on them:

for k1 in adict:
    x = []
    for t, record in sorted(adict[k1].items(), key = lambda(k,v):v['thedec']):
        x.append(record['theint'])
    y = [0]*(len(x)/2)
    for i in xrange(0,len(x),2):
        y[i/2] = sum(x[i:i+2])

I am wondering if: 1. There is a faster way to extract the values of 'theint' than to use .append() 2. There is a way that I can take, for example, the average of all 'theint' values 3. There is a way that I can loop through a dictionary in two's so that I could somehow skip the step of first copying all of the values, and go immediately to adding them to a vector as summed pairs.

Thanks for the help.

cdelsola
  • 407
  • 2
  • 8
  • 17

1 Answers1

3
>>> [x['theint'] + y['theint'] for x, y in zip(*[iter(sorted(adict['key1'].values(), key=operator.itemgetter('thedec')))] * 2)]
[759, 1010, 450]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • @ignacio Vazquez-Abrams, thanks for that. I tried to take that apart. I don't really understand what [iterator_object] means. Any how can we use zip on an iterator object? I understand what this code does, but not how. Care to explain? – cdelsola Dec 13 '12 at 03:30