Home > front end >  Add key and list value to a dictionary
Add key and list value to a dictionary

Time:08-20

I have this basic list dictionary {'2011': ['William', 'George', 'Nancy'], '2012': ['Joe', 'Math']} that I want to add a key and list but it doesn't work

here my code:

 my_dict = {"2011": ["William", "George", "Nancy"], "2012": ["Joe", "Math"]}
   
    new_years = "2013"
    new_name = ["Alex", "Markus"]

    my_dict.update[new_years: new_name]
    print(my_dict)

Here is the excepted output that I am looking for:

{'2011': ['William', 'George', 'Nancy'], '2012': ['Joe', 'Math'], '2013': ["Alex", "Markus"]}

CodePudding user response:

Your syntax is not valid Python, see this:

my_dict = {"2011": ["William", "George", "Nancy"], "2012": ["Joe", "Math"]}

new_years = "2013"
new_name = ["Alex", "Markus"]

my_dict.update({new_years: new_name})

# or my_dict[new_years] = new_name
print(my_dict)
  • Related