Python aggregate dictionary by key
I'm quite new to Python and just started working with dictionaries. I have the following question: Given the following dictionary:
How could I sum the population over countries? Thank you!
Avihoo Mamka 4,5163 gold badges30 silver badges42 bronze badges asked Dec 13, 2016 at 10:06
Patrick BaladaPatrick Balada 1,2701 gold badge18 silver badges35 bronze badges You can use
Output:
answered Dec 13, 2016 at 10:25
You iterate the main dictionary and add population to a new dictionary that maps a country to population. If using Python 3, do answered Dec 13, 2016 at 10:09
Rok PovsicRok Povsic 4,4065 gold badges36 silver badges48 bronze badges 1 You can go inside the dict iterating on the key:
answered Dec 13, 2016 at 10:10
Marco smdmMarco smdm 9921 gold badge13 silver badges24 bronze badges You can use The code looks like:
And the result is:
answered Dec 13, 2016 at 10:13
Avihoo MamkaAvihoo Mamka 4,5163 gold badges30 silver badges42 bronze badges How to group dictionary in Python by key?Group List of Dictionary Data by Particular Key in Python can be done using itertools. groupby() method.
Can the key of a dictionary be a set Python?Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
|