Home > Software engineering >  How to change dictionary key value from a list to a single int or float in python?
How to change dictionary key value from a list to a single int or float in python?

Time:10-26

Starting from a dictionary with values stored as a list for example:

ID_TypeDict = {2: [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0], 3: [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0], 4: [1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]}

My objective is to sum the list values and assign that value as an int or float to the dict key. To start I did the following:

TypeSum = dict(zip(ID_TypeDict.keys(), [[sum(item)] for item in ID_TypeDict.values()]))

Which returns the values as a list with a single float value :

{2: [1.0], 3: [1.0], 4: [2.0]}

How can I just assign the dict value to the key w/o the list? I tried to assign the values in place of the list object (code snippet below), but that was not the right approach as it doesn't change anything:

for val in TypeSum.values():
    for item in val:
        val = [0]

What would be an efficient yet best practice way to achieve this? Should it be done in the same line of code that generates the TypeSum dict (sums the list values)? Or handled after the fact? Thanks in advance.

CodePudding user response:

Just use the dict-comprehension, where you can assign the aggregate value calling the function for the list for each keys.

>>> {k:sum(v) for k,v in ID_TypeDict.items()}
{2: 1.0, 3: 1.0, 4: 2.0}

CodePudding user response:

You are wrapping the sum into a list. You can use the following if you prefer the functional approach usiung zip or the dict comprehension PyGuy answered with:

type_sum = dict(zip(ID_TypeDict, map(sum, ID_TypeDict.values())))
  • Related