Python Forum
simple list check with loops
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
simple list check with loops
#11
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...
Reply
#12
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.
Reply
#13
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?
Reply
#14
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
Reply
#15
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 Confused

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]
Reply
#16
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)
Reply
#17
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.
Reply
#18
if you want to type-in the json then use double quotes, not single quotes:

{"loki": "ch", "josh": "mi", "ryan": "th"}
Reply
#19
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
Reply
#20
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'}
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with to check an Input list data with a data read from an external source sacharyya 3 410 Mar-09-2024, 12:33 PM
Last Post: Pedroski55
  [solved] list content check paul18fr 6 707 Jan-04-2024, 11:32 AM
Last Post: deanhystad
  for loops break when I call the list I'm looping through Radical 4 896 Sep-18-2023, 07:52 AM
Last Post: buran
  How to solve this simple problem? Check if cvs first element is the same in each row? thesquid 2 1,233 Jun-14-2022, 08:35 PM
Last Post: thesquid
  check if element is in a list in a dictionary value ambrozote 4 1,976 May-11-2022, 06:05 PM
Last Post: deanhystad
  How to check if a list is in another list finndude 4 1,843 Jan-17-2022, 05:04 PM
Last Post: bowlofred
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,509 Aug-12-2021, 04:25 PM
Last Post: palladium
  Using recursion instead of for loops / list comprehension Drone4four 4 3,151 Oct-10-2020, 05:53 AM
Last Post: ndc85430
  how to check if string contains ALL words from the list? zarize 6 7,242 Jul-22-2020, 07:04 PM
Last Post: zarize
  Creating a List with many variables in a simple way donnertrud 1 2,041 Jan-11-2020, 03:00 PM
Last Post: Clunk_Head

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020