-1

I have created a dictionary containing majors and corresponding average salaries. I used a for loop to print the keys of the dictionary (being the majors) for a user to pick from. When I run the for loop at the end of the print statements, I keep getting the key None even when specifying to not print None using an if statement.

Here is the dictionary I defined:

majors = {
    'Management Information Systems': 84219,
    'Business': 50670,
    'Ecology': 58756,
    'Psychology': 40858,
    'Sociology' : 58678,
}

And here is the for loop I used to print the keys:

def printMajors():
    for key in majors.keys():
        if key is not None:
            print(key)

I also tried deleting the keys with the value None using the following (defined before the print statement):

  for key, value in majors.copy().items():
      if value is None:
          del majors[key]

Output:

Management Information Systems
Business
Ecology
Psychology
Sociology
None // this is unexpected and what I am having trouble with removing

Any help would be much appreciated!

accdias
  • 5,160
  • 3
  • 19
  • 31
  • Does this answer your question? [Efficiently Iterating over dictionary list values by skipping missing values Python 3](https://stackoverflow.com/questions/29875166/efficiently-iterating-over-dictionary-list-values-by-skipping-missing-values-pyt). Also: [Proper way to remove keys in dictionary with None values in Python](https://stackoverflow.com/questions/33797126/proper-way-to-remove-keys-in-dictionary-with-none-values-in-python) – kmoser Dec 05 '22 at 03:41
  • 2
    Can you post an actual example of your dictionary? I mean, one containing the keys with `None` values. If the dictionary is really the one you posted, the most probable cause is the one described in the answer posted by @JayPeerachai. – accdias Dec 05 '22 at 04:04
  • 1
    When I all `printMajors()` with you input it doesn't print `None`. It prints the expected five lines. However, doing `print(printMajors())` prints exactly the output you describe for the reason describe by @JayPeerachai below. – Mark Dec 05 '22 at 04:32

2 Answers2

2

I think you call printMajors() like below:

print(printMajors())

This returns None because your function doesn't return anything (no return statement). The function contains print() inside so there is no need for print() outside anymore.

solution:

printMajors()
JayPeerachai
  • 3,499
  • 3
  • 14
  • 29
0
majors = {
  'Management Information Systems': 84219,
  'Business': 50670,
  'Ecology': 58756,
  'Psychology': 40858,
  'Sociology' : 58678,
}

for i,j in majors.items():
    print(i)
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Dec 05 '22 at 10:48