[英]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.我是 Python 的新手,所以我仍在为很多简单的事情苦苦挣扎。 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.我希望我的最终 output 是“电”的浮点值的总和,但第一个键
('1388534400000', '1388538000000',...)
发生了变化。 How do I do that in python considering dictionaries are not indexable?考虑到字典不可索引,我该如何在 python 中做到这一点? 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'.
在从网站提取信息并从另一个具有 2 个子集的字典中提取信息后,我从 json 文件中获取了这本字典:“元数据”和“数据”。
I have tried dictionary.values()
but it returns a dict_values containing the pairs 'electricity' and the respective float value.我已经尝试过
dictionary.values()
但它返回一个 dict_values 包含对“电”和相应的浮点值。
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)
Assuming, you will always have a key electricity
in the values, you could just sum
the value of electricity
like,假设,您将始终在值中有一个关键的
electricity
,您可以将electricity
的价值sum
,例如,
>>> 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
sum = 0
for key in dict:
try:
dict[key] + 2.04
sum += dict[key]
except TypeError:
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.