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).
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
For Python 2.x:
for key, value in d.iteritems():
For 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
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.