Jan-06-2017, 08:31 PM
Both list and dict are data structures or containers.
You can access list element by index. List by design are ordered. You can have same element multiple times in the list.
Dict is not ordered by design. you have key:value pairs. You access the value using the key. So keys are unique (you cannot have the same key multiple times in the dict).
That's very very basic explanation. You should read the docs and/or some tutorial, e.g. dict and lists
from practical point of view, here are two cases that show the benefits of using dict vs. list
I. what is the password for given user. e.g. what is the password for ryan? with list of lists as in your current design you should iterate over list elements (the users), check if the name is ryan (i. .e. usr[0]) if usr[0] is ryan, return usr[1] (i.e. the password). You should loop over elements every time you want to get some user password. With dict you just get the value (the password) associated key ryan. See the performance difference?
following is correct code
You can access list element by index. List by design are ordered. You can have same element multiple times in the list.
Dict is not ordered by design. you have key:value pairs. You access the value using the key. So keys are unique (you cannot have the same key multiple times in the dict).
That's very very basic explanation. You should read the docs and/or some tutorial, e.g. dict and lists
from practical point of view, here are two cases that show the benefits of using dict vs. list
I. what is the password for given user. e.g. what is the password for ryan? with list of lists as in your current design you should iterate over list elements (the users), check if the name is ryan (i. .e. usr[0]) if usr[0] is ryan, return usr[1] (i.e. the password). You should loop over elements every time you want to get some user password. With dict you just get the value (the password) associated key ryan. See the performance difference?
users_list = [['josh' , 'mi'], ['ryan' , 'th'], ['loki' , 'ch']] for user in users_list: if user[0] == 'ryan': print (user[1]) break # this will exit the loop once name ryan is foundvs.
users_dict = {'josh':'mi', 'ryan':'th', 'loki':'ch'} print users_dict['ryan']II. Keys are unique and actually you want the same for the usernames. Already that should hint in the direction that maybe the dict is better choice for the task
following is correct code
users_list = [['josh' , 'mi'], ['josh' , 'ns'], ['ryan' , 'th'], ['loki' , 'ch']]while following is not
users_dict = {'josh':'mi', 'josh':'ns', 'ryan':'th', 'loki':'ch'}Of course there is a lot more to be said about lists vs. dict and their usage...