Python Dictionaries - Screen 4/8

How come the dictionary populates without using loop and the append syntax unlike we do in the list? I mean what’s the logic behind the difference in populating both??

Hello @mursuljamil

Different data structure has different methods of populating them. Like you said, we use append method for lists for populating them. In the case of a dictionary, you could use a for loop for populating them, without the for loop, this is the method:

dictionary_name['key'] = 'value'

And if you want a method like append for dictionary, you could use update method. It syntax looks like this:

dictionary_name.update({'key': 'value'})

Just remember that different data structures have different methods or ways to populate them.

Hi @mursuljamil ,

Great question. Lists and Dictionaries are data types or classes in Python. Lists and Dictionary data types are used to store data . Each data type has a group of built in methods that are available when you create that data type.

When you create a new List data type like in your exercise example (content_ratings list), the .append() method can be used to add new items to the List. You can also add items to a list by:

a_list = [89,8,“hi”]
a_list = a_list + [1000]



[89, 8, ‘hi’, 90, 1000]

From the simple above example, you can add items to a_list by using .append or by “+”. The .append() is shorter than writing a_list = a_list + [new item] especially if using a loop.

list_of_paint_colors = [red, blue, yellow, orange]
for color in list_of_paint_colors:
# add each color to a_list
a_list = a_list + [color]

[89, 8, ‘hi’, 90, 1000, ‘red’, ‘red’, ‘blue’, ‘blue’, ‘yellow’, ‘yellow’, ‘orange’, ‘orange’]

The color was added using either the .append() or “+”

Just like the List data type has builit in methods, the Dictionary data type has built -in methods and ways to populate the dictionary but the .append() method is not accessible by Dictionary objects.
In order to add an item to a dictionary you use the following syntax:
dictionary[key] = value
a_price_list = {“sheets”:89.00, “books”:20, “phones”:34.00}
#add a new item to a_price_list
a_price_list[“notebooks”] = 3.00

dict (<class ‘dict’>)
{‘books’: 20, ‘notebooks’: 3.0, ‘phones’: 34.0, ‘sheets’: 89.0}

I have provided the below link to the Python 3.10 documentation of all the methods of list objects: 5. Data Structures — Python 3.10.6 documentation

I have also provided a link to the Python 3.10 documentation of all the methods of dictionary objects: 5. Data Structures — Python 3.10.6 documentation