In: Computer Science
Through Python, a dictionary or list is often used to store a sequential collection of elements. Suppose, for instance, that you need to read 50 numbers, compute their average, and then compare each number with the average to determine whether it is below or above the average. In order to do this (without the use of list), you would first declare 50 variables to store the 50 numbers. This means you would have to create 50 variables and repeatedly write almost the identical code 50 times. Writing a program this way is impractical. To overcome this issue, you can make use of a list to store all the 50 numbers and access them through a single list variable.
For your initial post, describe the difference between dictionary and list in Python and explain when each would be used. Provide an example of how each dictionary and list would be implemented within Python. 250 WORDS
hello,
let us differentiate between both i.e., List and Dictionary:-
List:-
List is a data structure which is defined in to store multiple values within a same variable which is accessed by an index element.
List are more like an array of data but there is no restriction over the type of data stored in a list, as example a list can store any type of data simultaneously like, a list of four element can have values of type integer, float, string, bool.
syntax for defining of a list in python is:-
list_name=[]
example of a list :-
mydata=[1,'Jonney English,3.456,True] #list shown here have four type of value stores simultaneously
the elements of a list can be accessed by index as example:-
mydata[0]=1
mydata[1]='jonney English'
myadata[2]=3.456
mydata[3]=True
List are mutable which means values stored in list can be changed , as example
mydata[3]=False
now the new list will become:-
mydata=[1,'Jonney English,3.456,False]
Dictionaries:-
dictionaries are also like list but differ in the way that they have keys instead of index .
i.e., they are accessed using user defined keys.
these are also mutable and can be changed/updated.
the elements inside a list may not be arranged in sequential order as they were in list, ( since each element is recognized by key and not by index)
syntax for defining a dictionary:-
dict_name={}
adding elements to dictionary
dict_name['key']=value
accessing elements of dictionary using keys:-
print(dict_name['key'])
example:-
person={}
person['pet']='dog'
person['home']='texas'
person['salary']=$70000
so now the dictionary will look like:-
person={'pet':'dog', 'home':'texas', 'salary':'$70000'}
When should we use any of these:-
List should be used when there is a specific order in which elements are stored
while
dictionary should be used when there is no restriction in order of element and where elements can be accessed using keys.
i hope i was able to solve your problem to a greater extent, please feel free to comment your queries, Please consider my efforts and upvote my solution.
Thanku:)