Home > database >  How do I append items to a list within a dictionary?
How do I append items to a list within a dictionary?

Time:10-30

How can I append to a list within a dictionary?

I just wanted to add Tim as the fourth student, with an ID of 012. I can't understand why the below isn't working?

studName = ['Joe', 'Mac', 'Bob']
studID = ['123', '456', '789']

student_dictionary = dict(zip(studName, studID))
print(student_dictionary)

student_dictionary[studName].append('Tim')
student_dictionary[studID].append('012')
print(student_dictionary)

CodePudding user response:

You can do this to append item to the dictionary:

student_dictionary["Tim"] = "tim's id"

CodePudding user response:

What you tried isn't working because student_dictionary has no key studName, which you should see when you print it. You're also asking how to append to a list within a dictionary, which is possible, but not in this case because your dictionary does not contain any lists. You can do what the other user suggested:

student_dictionary["Tim"] = "012"

Or, you can add "Tim" and "012" to your lists and reconstruct the dictionary using the zip method like you did before.

Edit: Additionally, studName can never be a dictionary key because it is a list and dictionary keys must be hashable types like int, str, etc. That's why when you try to do student_dictionary[studName], you get the error:

TypeError: unhashable type: 'list'

CodePudding user response:

Your code doesn't work because you're trying to use lists as dictionary keys. Meanwhile, your dictionary values aren't lists, they are strings

Why not just append to the lists before creating the dict?

studName.append('Tim')
studID.append('012')

student_dictionary = dict(zip(studName, studID))
print(student_dictionary)
  • Related