-4

My dictionary looks like this:

my_dict = {
   '0': ['1'].
   '3': ['2'].
   '1': ['0', '9', '3'].
   '4': ['1', '4'].
}

User will input a key and value. My function will delete that value from key, value pairs.

def deleteVal (my_dict, key_val, val):
   # write your function here

If any user removes a value from a key-value pair that has only 1 value, it will remove the entire key. For example: if user remove value 1 from 0, the function will delete entire 0 key as it doesn't have any value left.
How can I do that?

  • What have you tried? You did a great job describing the desired logic, the function writes itself – Cireo Jun 05 '21 at 04:39
  • Subclass dict or write code – dawg Jun 05 '21 at 04:39
  • @Cireo Actually, I googled for half an hour. Didn't find anything suitable. – Munshi Saif Jun 05 '21 at 04:49
  • Not to be too harsh, but I see 18M results for 'python remove element from list', 4.5M results for 'python remove key from dictionary', and 102M results for 'python check if list is empty'. 30 minutes doesn't really cover no code – Cireo Jun 05 '21 at 04:52

1 Answers1

0
def deleteVal (my_dict, key_val, val):
    if len(my_dict.get(key_val, "1"))>1:
        try:
            my_dict[key_val].remove(val)
        except ValueError:
            pass 
    else:
        my_dict.pop(key_val, None)
dawg
  • 98,345
  • 23
  • 131
  • 206
  • 1
    val -> key_val in your `else`, and your len check is wrong, if you want to be full safe might also want to check key_val is present at all – Cireo Jun 05 '21 at 04:53
  • @Cireo: *val -> key_val in your else* agreed; fixed. *your len check is wrong* don't agree; *if you want to be full safe might also want to check key_val is present at all* gotta leave something for the OP to do! – dawg Jun 05 '21 at 05:02
  • 1
    fair enough, there will be funny corner cases regardless of the implementation ;) – Cireo Jun 05 '21 at 05:04
  • @CireoL See [How can I remove a key from a Python dictionary?](https://stackoverflow.com/a/11277439/298607) No need to check for the key's existence... – dawg Jun 05 '21 at 05:12
  • Don't need a long comment chain, just saying you will throw KeyError before you get to `pop` – Cireo Jun 05 '21 at 05:15
  • No you don't throw a `KeyError` if you use the default argument to `pop`; the default value is returned if the key is not present. Try it... – dawg Jun 05 '21 at 05:16
  • You *could* throw a KeyError at the `len` test but not at the `pop` – dawg Jun 05 '21 at 05:18
  • Yes, I'm just saying that `len(items[key])` will always be executed before `items.pop(key, None)` – Cireo Jun 05 '21 at 05:28
  • 1
    @Cireo: Fixed using `.get`. Thanks – dawg Jun 05 '21 at 13:19