Lele
Lele

Reputation: 13

Is there a way of extracting float values from a python dictionary?

I'm new to Python so I'm still struggling with a lot of simple things. I have a dictionary with the following structure:

<class 'dict'>
{'1388534400000': {'electricity': 0.0}, '1388538000000': {'electricity': 0.0}, '1388541600000': {'electricity': 0.0},...}

I want my final output to be the sum of the float values of 'electricity' but the first key ('1388534400000', '1388538000000',...) changes. How do I do that in python considering dictionaries are not indexable? I got this dictionary from a json file after extracting the information from a website and extracting it from another dictionary that had 2 subsets: 'metadata' and 'data'.

I have tried dictionary.values() but it returns a dict_values containing the pairs 'electricity' and the respective float value.

This is the code I'm using:

r = s.get(url, params=args)
packages_json = r.json()
print(packages_json)
print(type(packages_json))
package_json = packages_json['data']
print(type(package_json))
print(package_json)

Upvotes: 1

Views: 449

Answers (2)

han solo
han solo

Reputation: 6600

Assuming, you will always have a key electricity in the values, you could just sum the value of electricity like,

>>> d
{'1388534400000': {'electricity': 0.0}, '1388538000000': {'electricity': 0.0}, '1388541600000': {'electricity': 0.0}}
>>> sum(v['electricity'] for k,v in d.items())
0.0

or just,

>>> sum(v['electricity'] for v in d.values())
0.0

And, maybe use the latter, because i did a benchmark,

>>> import timeit
>>> timeit.timeit("sum(v['electricity'] for k,v in d.items())", setup="d={'1388534400000': {'electricity': 0.0}, '1388538000000': {'electricity': 0.0}, '1388541600000': {'electricity': 0.5}}")
0.4952311920005741
>>> timeit.timeit("sum(v['electricity'] for v in d.values())", setup="d={'1388534400000': {'electricity': 0.0}, '1388538000000': {'electricity': 0.0}, '1388541600000': {'electricity': 0.5}}")
0.4470630470004835

Upvotes: 3

eladgl
eladgl

Reputation: 69

sum = 0
for key in dict:
    try:
        dict[key] + 2.04
        sum += dict[key]
    except TypeError:
        pass

Upvotes: -1

Related Questions