Posts: 8,160
Threads: 160
Joined: Sep 2016
Jan-06-2017, 08:31 PM
(This post was last modified: Jan-06-2017, 08:34 PM by buran.)
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?
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 found vs.
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...
Posts: 67
Threads: 9
Joined: Jan 2017
Your explanation was awesome and thank you for helping me with at least a basic description of each and the usage. I really appreciate the time you took to do that for me and now I can implement what you have taught me into more codes in the future. It was very helpful and my sincerest apologies for being so questioning.
Posts: 67
Threads: 9
Joined: Jan 2017
Jan-08-2017, 05:33 AM
(This post was last modified: Jan-08-2017, 05:35 AM by Low_Ki_.)
Ok so now my question is, how would I retrieve dict data from a file, update it to a dict in my program, then write the new username / password recieved to the end (append) of the dict in the file as a key:value pair?
e.g with a list I would retrieve data like so:
usrdatalist = []
# Open file to read
with open("usrdata", "r") as usrinfo:
for l in usrinfo:
un, pw = l.split(',')
usrdatalist.append([un, pw]) and then write the new data after getting the username and password info from user like so:
with open("usrdata", "a") as usrinfo:
usrinfo.write(username+','+password+'\n') How would I go about changing this to fit a dict?
Posts: 12,031
Threads: 485
Joined: Sep 2016
Jan-08-2017, 05:53 AM
(This post was last modified: Jan-08-2017, 05:54 AM by Larz60+.)
One of the best ways to save dictionaries is using JSON.
It's simple to use and saves a lot of work.
An added feature is that the json format is plain text, so you can
open a file and examine the dictionary with a simple text editor.
here's some sample code:
import json
usrdatalist = {'josh':'mi', 'ryan':'th', 'loki':'ch'}
# To save the dictionary
with open("UserData.json", "w") as f:
j = json.dumps(usrdatalist)
f.write(j)
# To load the data (I'll use a different dictionary for the example)
newdict = dict()
with open("UserData.json", 'r') as f:
j = f.read()
newdict = json.loads(j)
print(newdict) results:
Output: {'loki': 'ch', 'ryan': 'th', 'josh': 'mi'}
Process finished with exit code 0
You can save other structures, lists for example, as well
Posts: 67
Threads: 9
Joined: Jan 2017
Thank you Larz for the reply my friend. I think I'm catching on to how to use the syntax for dict() except when it comes to reading from file. I get a weird error in the following code:
import json
usrdatalist = dict()
# Open file to read
with open("usrdata.json", 'r') as f:
j = f.read()
usrdatalist = json.load(j) Error: /usr/bin/python3.5 /root/PythonProjects/video_game/registry.py
Traceback (most recent call last):
File "/root/PythonProjects/video_game/registry.py", line 10, in <module>
usrdatalist = json.loads(j)
File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Process finished with exit code 1
I don't understand because I don't actually have anymore than 7 lines in the code at this point. LOL
Not sure if it matter at all but I typed this into the json file just for testing purposes.
[Image: Screenshot%20from%202017-01-08%2001-14-2...fmzshy.png]
Posts: 8,160
Threads: 160
Joined: Sep 2016
Obviously the UserData.json file from the screenshot is not created with the code... Note that json format uses double-quotes, not single. Also, you should learn to read and understand traceback messages. It clearly states what the problem is: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Posts: 67
Threads: 9
Joined: Jan 2017
Okay, so I need to create the json with the code then implement the read, get user info, and write as functions. I know this is probably tedious for you guys but I don't simply want someone to write me a complex program and copy and paste the code of someones work. I would like to get there in due time on my own and write the code out myself. I've ordered "The Great Courses - How to Program. Computer Science Concepts and Python Exercises from Texas A&M Professor John Keyser. So that should help a tad I'm guessing.
Posts: 8,160
Threads: 160
Joined: Sep 2016
if you want to type-in the json then use double quotes, not single quotes:
{"loki": "ch", "josh": "mi", "ryan": "th"}
Posts: 12,031
Threads: 485
Joined: Sep 2016
Jan-08-2017, 12:21 PM
(This post was last modified: Jan-08-2017, 12:21 PM by Larz60+.)
Was the file originally created as JSON? if not, you cannot read it as such.
It will have to be converted.
Rather than posting graphics, please use output tags
tags for tracebacks. You can cut and paste the data
Images look messy and are undesirable
Posts: 7,319
Threads: 123
Joined: Sep 2016
Jan-08-2017, 01:42 PM
(This post was last modified: Jan-08-2017, 01:42 PM by snippsat.)
There are unnecessary step in your example @ Larz60+.
There is no need for read() and write() ,
and json.load() do return a Python dictionary.
import json
usrdatalist = {'josh':'mi', 'ryan':'th', 'loki':'ch'}
with open("my_file.json", "w") as j:
json.dump(usrdatalist, j)
with open("my_file.json") as j_data:
saved_record = json.load(j_data)
print(type(saved_record))
print(saved_record) Output: <class 'dict'>
{'josh': 'mi', 'loki': 'ch', 'ryan': 'th'}
|