简体   繁体   English

列表中的Python访问和字典值求和

[英]Python access and sum dictionary values in list

I would like to know how can I access list values in a dictionary to sum them: 我想知道如何访问字典中的列表值以求和:

{'key1': [3, 1], 'key2': [0, 4], 'key3': [57492, 204652], 'key4': [1,3]}

I would like to sum the first element of each list sum(3,0,57492,1). 我想对每个列表的第一个元素求和sum(3,0,57492,1)。

Is it possible to do so without any loop ? 是否可以这样做而没有任何循环?

Thank you in advance 先感谢您

You have to iterate over the entire dictionary which means you have to use loop. 您必须遍历整个字典,这意味着您必须使用循环。

It can simply be done with a list comprehension like: 只需使用列表理解即可,例如:

sum([values[0] for key, values in dictionary.items()])

If the number of items in the dictionary are large in number then instead of dictionary.items() you can use a generator function 如果字典中的项目数很大,则可以使用生成器函数来代替dictionary.items()

For Python 2.x: 对于Python 2.x:

for key, value in d.iteritems():

For Python 3.x: 对于Python 3.x:

for key, value in d.items():

You can read more on how to do list comprehension here: Link 您可以在此处阅读有关列表理解方法的更多信息: 链接

Iterating over a dictionary: Link 遍历字典: 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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