简体   繁体   中英

For looping through a Python dictionary

I'm trying to for loop through a dictionary and print the first float value of every row but I have no idea how to choose that I want just those values.

My dictionary:

{'abc': 123123, 'defg': [
    ['123.4', '10'],
    ['567.8', '10'],
    ['91011.12', '10']
]}

I want the output to be:

123.4
567.8
91011.12

Also I want to sum those values. Is there easier way to do that with SUM method without looping?

Thanks for the help! I'm really lost with this.

Ok I think I got it. Thanks to Ajax1234 and Jerfov2 for tips!

s = {'abc': 123123, 'defg': [
['123.4', '10'],
['567.8', '10'],
['91011.12', '10']
]}

For loop and print:

for x in s['defg']:
    print(x[0])

Outputs:

123.4
567.8
91011.12

And the summing with for loop:

summed = 0
for x in s['defg']:
    summed = summed + float(x[0])
print("%.2f" % summed)

Outputs:

91702.32

At the very end any functional approach in Python is just syntactic sugar, here are my 2 cents in a non-functional fashion:

import ast
import itertools

s = {'abc': 123123, 'defg': [
    ['123.4', '10'],
    ['567.8', '10'],
    ['91011.12', '10']
]}

def str_is_float(value):
    if isinstance(value, str):
        value = ast.literal_eval(value)
    if isinstance(value, float):
        return True
    else:
        return False

def get_floats(d):
    for k, v in d.items():
        if isinstance(v, list):
            for n in itertools.chain.from_iterable(v):
                if str_is_float(n):
                    yield float(n) 
        elif str_is_float(v):
            yield float(v)

floats = list(get_floats(s))

# Print all the floats
print(floats) 
# sum the floats
print(sum(x for x in floats))

You can use reduce for a more functional solution:

import re
import itertools
from functools import reduce
s = {'abc': 123123, 'defg': [
 ['123.4', '10'],
['567.8', '10'],
['91011.12', '10']
]}
new_s = list(itertools.chain(*[[float(c) for c in itertools.chain(*b) if re.findall('^\d+\.\d+$', c)] for a, b in s.items() if isinstance(b, list)]))
print(new_s)
print(reduce(lambda x, y:x+y, new_s))

Output:

[123.4, 567.8, 91011.12]
91702.32

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM