Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to walk through a python array/object similar to PHP's foreach function

I'm new to Python, sorry for asking such a probably simple question.

I'm hacking a script which has an Array(?) which I can print with the following command:

repr(Interfaces.log_manager.job_log[user_id])) gives me:

{
'3f2': ('3', 0.0078125, 1405595247.855199), 
'3f1': ('3', 0.00390625, 1405595247.855164), 
'3ed': ('2', 0.0078125, 1405595227.65275), 
'3ec': ('2', 0.00390625, 1405595202.852576), 
'3eb': ('2', 0.00390625, 1405595202.852538)
}

I know want to sum up the 2nd values in the parentheses and get the min and max value of the third in the parentheses.

In PHP this is possible with a foreach... How is that done in Python ?

My result should/would be:

sum = 0.0312496
mintime: 1405595202
maxtime: 1405595247

Any help very appreciated

thx

like image 476
biergardener Avatar asked Dec 07 '25 09:12

biergardener


2 Answers

First of all your data structure is dict in python, so you should ;

for k,v in l.iteritems():
    print k,v

The output;

3ec ('2', 0.00390625, 1405595202.852576)
3ed ('2', 0.0078125, 1405595227.65275)
3f2 ('3', 0.0078125, 1405595247.855199)
3eb ('2', 0.00390625, 1405595202.852538)
3f1 ('3', 0.00390625, 1405595247.855164)
like image 140
myildirim Avatar answered Dec 09 '25 23:12

myildirim


Try this

>>> a = {'3ec': ('2', 0.00390625, 1405595202.852576), '3ed': ('2', 0.0078125, 1405595227.65275), '3f2': ('3', 0.0078125, 1405595247.855199), '3eb': ('2', 0.00390625, 1405595202.852538), '3f1': ('3', 0.00390625, 1405595247.855164)}
>>> min_val = min([x[2] for x in a.values()])
>>> max_val = max([x[2] for x in a.values()])
>>> sum_val = sum([x[1] for x in a.values()])
>>> print min_val, max_val, sum_val
1405595202.85 1405595247.86 0.02734375
like image 21
Nilesh Avatar answered Dec 09 '25 23:12

Nilesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!