CREATING DICTIONARIES Add A Key

Can we insert values in dictionaries with help of .append()??

Welcome to the forums.
Did you try to use the .append() method with a dictionary value? What happened?
In short, different data types have specific methods available to them that only work with those data types. Otherwise, you’ll get an error.

You can read here about list methods here:
https://docs.python.org/3/tutorial/datastructures.html

And updating dictionaries here:
https://docs.python.org/3/tutorial/datastructures.html#dictionaries

and here:
https://www.askpython.com/python/dictionary/how-to-update-a-python-dictionary

2 Likes

yes i tried using .append() method but its showing key error
the code was:
animals_in_zoo={}
animals_in_zoo[“zebras”].append(8)
animals_in_zoo[“monkeys”].append(12)
animals_in_zoo[“dinosaurs”].append(0)
print(animals_in_zoo)

The output was:
Traceback (most recent call last):
File “script.py”, line 2, in
animals_in_zoo[“zebras”].append(8)
KeyError: ‘zebras’

The error tells us there is no such key as ‘zebras’. The append() method is a list attribute, not dict.

If what you are assigning is a value, then use assignment…

animals_in_zoo['zebras'] = 8

That will insert the key and associated value into the dictionary.

3 Likes

ok , got it thank you sir

1 Like