1

If I had a dictionary like the following (whole dictionary is omitted to make this readable):

{"'hood": '-0.375',
 '-0.4': '',
  '0': '-0.375',
  '101': '-0.25',
  '105': '-0.25',
  '300': '-0.25',
  '3tc': '-0.25',
  '400': '-0.25',
  'FALSE': '-0.486111111',
  'TRUE': '0.259615385',
  }

and a list like the following:

['This', 'is', 'a', 'media', 'player', 'that', 'is', 'FALSE', 'TRUE']

how could I go through the dictionary and check if a word from the list exists in the dictionary and if it does exist, add up its value associated with the word? My goal is to have a final number that represents the sum of the values from the dictionary when the key word from the list exists.

For example, in my list above the words 'FALSE' and 'TRUE' are in the list and since those two words are also present in the dictionary above, I would add their values of -0.486111111 and 0.259615385 together to create a single number as the final output.

I also realize that the values for the dictionary are strings so I would have to convert those to numbers to properly add them.

I have tried to loop through the list and check if it is present in the dictionary that way but I am having issues.

1
  • 1
    Also see Stack Overflow guidance on homework. Simply dumping your assignment here is unacceptable.
    – Prune
    Commented Feb 4, 2021 at 23:55

2 Answers 2

3

The answer to the question in the title is with a comprehension:

sum(my_dict[key] if key in my_dict else 0 for key in my_list)

However, in the example provided, there are a few oddities. Firstly, the numbers in the dictionaries are in quotation marks that means they count as strings. Before summing them, they should be turned into floats so my_dict[key] becomes float(my_dict[key]). Secondly, the boolean values for true/false in python are True and False, putting them in quotation marks just turns them into strings. It doesn't break anything here, but it is unusual and worth mentioning.

2
  • I see what you mean. The reason 'TRUE' and 'FALSE' exist in that format is because I created the dictionary from a text file with two columns where true and false were written as 'TRUE' and 'FALSE'. Thank you for your help. Commented Feb 4, 2021 at 23:54
  • Sure, data rarely comes in the forum that we would want haha. If the answer works for you, you can also accept it. Commented Feb 4, 2021 at 23:57
3

Same logic as ScienceSnake's nice answer, but with modifications of a) converting to float during the operation and b) using get to deal with keys not in the dict:

sum(float(my_dict.get(i, 0)) for i in my_list)

Not the answer you're looking for? Browse other questions tagged or ask your own question.