Home > Net >  How can I add float values together from a dictionary of mixed lists?
How can I add float values together from a dictionary of mixed lists?

Time:12-09

I am trying to add together values from mixed-value lists in a dictionary:

sampledict = {key1:[str1,float1],key2:[str2,float2], key3:[str3,float3]}

all_floats = float1 float2 float3

I will preface that I am fairly new to coding so I apologize for any lack of clarity.

I tried a TypeError exception to isolate the floats, but ran into errors. I tried using sum(), but it didn't like the mixed data type.

CodePudding user response:

  • Each value in your dictionary is a list.
  • In each list, the float you care about is the second element.
  • So for each value in your dictionary, you want to add up the second element of that list

Let's do that:

total = sum(value[1] for value in sampledict.values())

Or, if you want a regular loop, initialize total=0 before the loop, and then keep adding value[1] to it inside the loop:

total = 0
for value in sampledict.values():
    total  = value[1]

CodePudding user response:

This is how I'd probably do it:

Step 1: gather all the data...

my_dict = {
    'key1':["str1", 1.0112, 1],
    'key2':["str2", 2.3121, 5], 
    'key3':["str3", 1.5123, 'z']
}

# this grabs all the values using list instantiation and puts them in one list
all_values = sum([ value for key,value in my_dict.items() ], [])
  1. Iterate over the list of items and take only the type you want
# iterrate over that list and select only the ones of type float (or whatever)
floats     = [ value for value in all_values if type(value) == float ]
  1. Add up the floats (or whatever)
print(sum(floats))
  • Related