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 = {}?

5
  • 1
    Possible duplication: stackoverflow.com/questions/23177439/… Commented Jul 18, 2021 at 4:08
  • you can use if dic: a = min(dic, key=dic.get) Commented Jul 18, 2021 at 4:09
  • 1
    An empty dictionary is not equal to None. Commented Jul 18, 2021 at 4: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? Commented Jul 18, 2021 at 4: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. Commented Jul 18, 2021 at 4:20

2 Answers 2

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) 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.