简体   繁体   中英

Why can't I append a string object to a dictionary

I am new to python and was just creating a program that manages student records like a database but for some reason I am not able to append a string object into a dictionary data structure. Any reason why?

def main():

# Create an empty dictionary

database = {'FIRST_NAME':'Default', 'LAST_NAME':'Default', 'ID_NUMBER':'Default'}

# Create a menu

print('\t\t\t Student Database program')
print('K: Enter student information')
print('D: Display student information')

option = input('Enter an option')

# Create a decision structure

if option == 'k' or option == 'K':
    # ask the user to enter in a student first name + last name + id number
    firstName = input('enter the students first name: ')
    lastName = input('enter the students last name: ')
    idNumber = int(input('enter the students ID number: '))

    # append these into the empty database
    database['FIRST_NAME'].append(firstName) // The error is most likelyhere
    database['LAST_NAME'].append(lastName) // The error is most likelyhere
    database['ID_NUMBER'].append(idNumber) // The error is most likely here

    print('Success!')

elif option == 'D' or option == 'd':
    # print out the values of each key
    print('Here are the students information')               
    print('')
    print(database['FIRST_NAME'])
    print(database['LAST_NAME'])
    print(database['ID_NUMBER'])

main()

You cannot "append" to a dictionary, you can update or add by using its key:value.

update:

dict_name.update({'item1': 1})

add:

dict_name['item3'] = 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM