If I have a dictionary such as:
my_dict = {\"A\": [1, 2, 3], \"B\": [9, -4, 2], \"C\": [3, 99, 1]}
How do I create a new dictionary with su
One liners- for the same, just demonstrating some ways to get the expected result,
my_dict = {"A": [1, 2, 3], "B": [9, -4, 2], "C": [3, 99, 1]}
Using my_dict.keys()
:- That returns a list containing the my_dict
's keys, with dictionary comprehension.
res_dict = {key : sum(my_dict[key]) for key in my_dict.keys()}
Using my_dict.items()
:- That returns a list containing a tuple for each key
value pair of dictionary, by unpacking them gives a best single line solution for this,
res_dict = {key : sum(val) for key, val in my_dict.items()}
Using my_dict.values()
:- That returns a list of all the values in the
dictionary(here the list of each lists),
note:- This one is not intended as a direct solution, just for demonstrating the three python methods used to traverse through a dictionary
res_dict = dict(zip(my_dict.keys(), [sum(val) for val in my_dict.values()]))
The zip
function accepts iterators(lists, tuples, strings..), and pairs similar indexed items together and returns a zip object, by using dict
it is converted back to a dictionary.