Perform operation on floats in list value that contains both floats and strings

Viewed 106

I have a dictionary in Python 3 in which all key-value pairs have the following structure:

my_dict = {'Jerry': [0.4, 'Queens', 0.6, 'Knicks']}


This means that the value is always a list with float, string, float, string.

I need to modify the values so that the two floats are averaged, and that the new dictionary looks as follows:

new_dict = {'Jerry': [0.5, 'Queens', 'Knicks]}

I have tried a for loop that selects the floats from the value list based on their indexes, but Python doesn't let me index through it.

for k, v in my_dict.items():
    average = sum(v[0], v[1])/2
    my_dict[k] = [average, v[1], v[3]]

This returns


TypeError: 'float' object is not iterable

How could I select the floats to work out the average?

3 Answers

You need to pass an iterable to the sum() function, so make the values v[0] and v[1] to a list by adding a [ and ]

With minimal modification to your code

my_dict = {'Jerry': [0.4, 'Queens', 0.6, 'Knicks']}

for k, v in my_dict.items():
    average = sum([v[0], v[2]])/2
    my_dict[k] = [average, v[1], v[3]]

print(my_dict)

Output:

{'Jerry': [0.5, 'Queens', 'Knicks']}

Or a shorter solution

my_dict = {'Jerry': [0.4, 'Queens', 0.6, 'Knicks'], 'Berry': [0.5, 'Queens', 0.1, 'Knicks']}

my_dict = {k:[(v[0]+v[2])/2, v[1], v[3]] for k,v in my_dict.items()}

print(my_dict)

Output:

{'Jerry': [0.5, 'Queens', 'Knicks'], 'Berry': [0.3, 'Queens', 'Knicks']}

Iterate through the key, value pairs, and create a temporary list to store numeric and string data, and iterate each value list and append to numbers/strings lists based on type, finally find the average and add it to the resulting dictionary.

my_dict = {'Jerry': [0.4, 'Queens', 0.6, 'Knicks']}
result = {}

for key,value in my_dict.items():
    numbers = []
    strings =[]
    for item in value:
        if type(item) is float:
            numbers.append(item)
        else:
            strings.append(item)
    result[key] = [sum(numbers)/len(numbers)] + strings

OUTPUT:

{'Jerry': [0.5, 'Queens', 'Knicks']}

PS: This solution will work even if you have more or less number of items in the value list of the given dictionary.

The first argument for sum() is supposed to take an iterable (e.g., a list).

You can either use average = sum([v[0], v[2]])/2 as suggested by @abhi-j or just average = (v[0]+v[2])/2.

Related