0

in python:

dic = {}    #start with an empty list

After this line, I did a series of command to add things to the dic. But there is also a situation where nothing is added. Then, I need to use the value in the dic.

a = min(dic, key=dic.get)

if there is nothing in the dic, it will give me an error: ValueError: min() arg is an empty sequence I don't need an output for a if dic is empty, so I then attempted to use the if statement to get away:

if dic == None: 
    pass
else:
    a = min(dic, key=dic.get)

but this will still give me the same error. Is there a way to skip this line of codea = min(dic, key=dic.get)when dic = {}?

evonc
  • 3
  • 1
  • 1
    Possible duplication: https://stackoverflow.com/questions/23177439/python-checking-if-a-dictionary-is-empty-doesnt-seem-to-work – namcao00 Jul 18 '21 at 04:08
  • you can use `if dic: a = min(dic, key=dic.get)` – deadshot Jul 18 '21 at 04:09
  • 1
    An empty dictionary is not equal to None. – John Gordon Jul 18 '21 at 04:10
  • In your own words: why do you think a dictionary that is empty should compare equal to `None`? In your own words: how do you write an empty dictionary? – Karl Knechtel Jul 18 '21 at 04:16
  • As a side note, to help you ask better questions in the future: try to be clear in your question title about *what is actually confusing you*. You know how to use `if`; you didn't know why the `if` condition wasn't working as you expected. It should be clear that there is only one possible point of failure: the condition that you're checking. Therefore, you should phrase the question that way - "why does this condition not check that a dictionary is empty?" or something along those lines. When you think more clearly like that, it also helps you find better Internet search terms. – Karl Knechtel Jul 18 '21 at 04:20

2 Answers2

1

The dic is of the <class dict> whereas the None object is of the <class 'Nonetype'>. So the given expression dic == Nonewill always return False. Instead change it to dic == {} or len(dic) == 0 or simply dic. An empty dictionary will usually evaluate to False.

if dic: 
 pass
else:
 a = min(dic, key=dic.get)
sushruta19
  • 327
  • 3
  • 12
0

Try changing the logic to:

if len(dic) == 0: 
    pass
else:
    a = min(dic, key=dic.get)

You current code skips over the pass block because even if the dict dic is empty, it is not None, there's a bunch of ways to check emptiness of a dict, personally, I'm a fan of checking the len as above but there are other way such as on this page.

Bernstern
  • 201
  • 1
  • 5