1

I want to append an empty list as the value when the name_input is not empty and grade_input is empty to a dictionary, whose keys are the name_input. The following is the code snippet. But it doesn't seem to work. Any suggestions?

if (name_input != '' and grade_input ==''):
        name_dic[name_input].append([])
idjaw
  • 25,487
  • 7
  • 64
  • 83
user3535492
  • 87
  • 1
  • 1
  • 6
  • 5
    You don't append to a dictionary. Just do this: `name_dic[name_input] = []` – idjaw Feb 23 '16 at 03:58
  • Do you have only one grade_input for each name_input? A dict of empty lists doesn't seem very useful. – John La Rooy Feb 23 '16 at 04:02
  • 1
    If you're trying to initialize as an empty list, you can try using a `defaultdict` (https://docs.python.org/3/library/collections.html?highlight=collections#collections.defaultdict). – beigel Feb 23 '16 at 04:27

1 Answers1

7

The .append() method applies to lists, not dictionaries.

To add a new key/value pair to a dictionary, simply do this:

name_dic[name_input] = []
ml-moron
  • 888
  • 1
  • 11
  • 22