-2

I am running into trouble with my current program. I have created the template of how I want my program to run. I don't run into any problems. One tweak I would like to make to it is being able to remove a key from my dictionary once the value is recognized as 0.

I am looking for help as I am currently stuck at a wall. I am trying to manipulate my dictionary in order to get rid of any keys with a value of 0. I have tried a couple different notations but I am struggling to find an answer to my question.

Here is my code

import win32com.client
import time

#Mail information

print("Thanks for using the Mail Count Email Generator!")
time.sleep(2)

print("Please enter the mail count for each bundle.")
time.sleep(2)


#List and Dictionaries
mail = [ "PT", "MVR", "MVT", "TABC", "COIN_OP", "COMPLEX", "PRIORITY PAYMENTS"]
bundle_result = {}
mail_today = {}
final_list = list()


#User input of the Bundles
for bundle in mail:
    bundle_value = input("How many {}? ".format(bundle))
    bundle_result.update({bundle: bundle_value})
  • I am looking for help as I am currently stuck at a wall. I am trying to manipulate my dictionary in order to get rid of any keys with a value of 0. I have tried a couple different notations but I am struggling to find an answer to my question. Sorry if my original post was not as insightful. I will update it now. Thanks again. – Duane Charles Oct 29 '18 at 16:10
  • Then you should probably explain with _what_ you are stuck. What do you want to achive, what happens, what should happen, what did you try to fix it ... minimize your code so it displays your problem, we do not need your code-blob that does 10 things beautifully if you have problem with 1 thing. We need code that reproduces that 1 thing that does not work so we can copy&paste it to help you fix it. – Patrick Artner Oct 29 '18 at 16:12
  • Yes sir! Thank you. – Duane Charles Oct 29 '18 at 16:14
  • Are you trying to modify the dict while iterating it? Thats always a problem. Do one loop over your dict and remember all keys that have values of 0, put them into a list f.e. `keys_to_delete`, then delete them: `for k in keys_to_delete: del your_dict_name_here[k]` – Patrick Artner Oct 29 '18 at 16:14

1 Answers1

1

I would try:

try:
    if d[key]==0:
        del d[key]
except KeyError:
    "no key present"
    pass

More info: Delete and element from a dictionary

amonowy
  • 188
  • 12