python: dictionary and if statements - python

I have a file to read and a dictionary.
If the file says:
sort-by username
I want the dictionary to be
d = {'sort-by': 'username'}
if the file says :
sort-by name
then I want the dictionary to be
d = {'sort-by': 'name'}
right now, I have:
if 'user' in line:
d['sort-by'] = 'username'
else:
d['sort-by'] = 'name'
however, even though the file says sort-by username, I keep getting
d = {'sort-by': 'name'}
why is this?

print dict(map(str.split,open("some_file.txt")))
assuming your file actually looks like your example
if you have any control it may be more appropriate to store your data as json

Related

Is there a way to write a correct-form json info to a .json file and read from it locally?

I am planning to use JSON file as a simple database, i am trying to append to it new entries and try to take my entries later.
This is the code i have:
import json
import time
try:
with open('json_database.json', 'r') as json_database:
profiles = json.load(json_database)
except FileNotFoundError:
profiles = []
while True:
answer = input('list info (l), write info (w), new info (a)').lower()
if answer == 'w':
break
elif answer == 'l':
print(profiles)
else:
username = input('username: ')
email = input('Email: ')
rating = input('Rating: ')
lichess_profiles.append({
'profile':{
'username': lichess_username,
'email': email,
'rating': rating
}
})
with open('json_database.json', 'w') as json_database:
json.dump(profiles, json_database)
Now i want to call the info from the JSON info ! thats what i added :
with open('json_database.json') as json_1:
result = json.load(json_1)
print(result['profile']['email'])
what is the reason of that ? what shall i add ?
i tried that code but it raise this error :
TypeError: list indices must be integers or slices, not str
The base item you are writing to the json file is a list, but you're treating it like a dictionary. It contains dictionaries, but you have to access it like a list:
print(result[0]['profile']['email'])
print(result[1]['profile']['email'])
# etc.

Editing Dictionary via User Input - Python

I am creating a program which requires the user to make changes to the dictionary. I can do these with a normal dictionary, however I was advised to hold my data in 'sub dictionaries' like the one below.
I've tried to see if I can get it working by having it change the values for all of the fields in each entry, but even that doesn't seem to be working. I am quite new to python so please bear with me!
VDatabase = {
"1200033944833": {
'MAP' : 'XXXX',
'CODE' : '0123',
'Method': 'R',
'Code1': 'S093733736',
'Reg ID' : '01'
}
Search = input("Search ACCOUNT:")
tmp_dict = VDatabase.get(Search, None)
print(tmp_dict if tmp_dict else "No ACCOUNT Found. \"{}\"".format(Search))
VDatabase["CODE"] = input("Enter CODE:")
print("Changing CODE...")
I was looking to change the value of CODE to whatever the user Input is.
Unfortunately it doesn't do anything, I can alter a regular Dictionary, so I think it's due to it being a 'sub-dictionary' so how would I access these values?
Here in the line,
VDatabase["CODE"] = input("Enter CODE:")
You are trying to change the value of 'CODE' directly in VDatabase but not inside the sub-dictionary that you have searched for.
Search = str(input("Search ACCOUNT:"))
tmp_dict = VDatabase.get(Search, None)
print(tmp_dict if tmp_dict else "No ACCOUNT Found. \"{}\"".format(Search))
VDatabase[Search]["CODE"] = str(input("Enter CODE:"))
print(VDatabase[Search])
or
tmp_dict['CODE'] = str(input("Enter CODE:"))
You will see that the main dictionary has changed.
I have changed the input type to str so that the value won't be integer while searching.

Writing JSON data in python. Format

I have this method that writes json data to a file. The title is based on books and data is the book publisher,date,author, etc. The method works fine if I wanted to add one book.
Code
import json
def createJson(title,firstName,lastName,date,pageCount,publisher):
print "\n*** Inside createJson method for " + title + "***\n";
data = {}
data[title] = []
data[title].append({
'firstName:', firstName,
'lastName:', lastName,
'date:', date,
'pageCount:', pageCount,
'publisher:', publisher
})
with open('data.json','a') as outfile:
json.dump(data,outfile , default = set_default)
def set_default(obj):
if isinstance(obj,set):
return list(obj)
if __name__ == '__main__':
createJson("stephen-king-it","stephen","king","1971","233","Viking Press")
JSON File with one book/one method call
{
"stephen-king-it": [
["pageCount:233", "publisher:Viking Press", "firstName:stephen", "date:1971", "lastName:king"]
]
}
However if I call the method multiple times , thus adding more book data to the json file. The format is all wrong. For instance if I simply call the method twice with a main method of
if __name__ == '__main__':
createJson("stephen-king-it","stephen","king","1971","233","Viking Press")
createJson("william-golding-lord of the flies","william","golding","1944","134","Penguin Books")
My JSON file looks like
{
"stephen-king-it": [
["pageCount:233", "publisher:Viking Press", "firstName:stephen", "date:1971", "lastName:king"]
]
} {
"william-golding-lord of the flies": [
["pageCount:134", "publisher:Penguin Books", "firstName:william","lastName:golding", "date:1944"]
]
}
Which is obviously wrong. Is there a simple fix to edit my method to produce a correct JSON format? I look at many simple examples online on putting json data in python. But all of them gave me format errors when I checked on JSONLint.com . I have been racking my brain to fix this problem and editing the file to make it correct. However all my efforts were to no avail. Any help is appreciated. Thank you very much.
Simply appending new objects to your file doesn't create valid JSON. You need to add your new data inside the top-level object, then rewrite the entire file.
This should work:
def createJson(title,firstName,lastName,date,pageCount,publisher):
print "\n*** Inside createJson method for " + title + "***\n";
# Load any existing json data,
# or create an empty object if the file is not found,
# or is empty
try:
with open('data.json') as infile:
data = json.load(infile)
except FileNotFoundError:
data = {}
if not data:
data = {}
data[title] = []
data[title].append({
'firstName:', firstName,
'lastName:', lastName,
'date:', date,
'pageCount:', pageCount,
'publisher:', publisher
})
with open('data.json','w') as outfile:
json.dump(data,outfile , default = set_default)
A JSON can either be an array or a dictionary. In your case the JSON has two objects, one with the key stephen-king-it and another with william-golding-lord of the flies. Either of these on their own would be okay, but the way you combine them is invalid.
Using an array you could do this:
[
{ "stephen-king-it": [] },
{ "william-golding-lord of the flies": [] }
]
Or a dictionary style format (I would recommend this):
{
"stephen-king-it": [],
"william-golding-lord of the flies": []
}
Also the data you are appending looks like it should be formatted as key value pairs in a dictionary (which would be ideal). You need to change it to this:
data[title].append({
'firstName': firstName,
'lastName': lastName,
'date': date,
'pageCount': pageCount,
'publisher': publisher
})

Searching and sorting in text files

I am fairly new to code and i have a problem in reading a text file.
For my code i need to ask the user to type in a specific name code in order to proceed to the code. However, there are various name codes the user could use and i don't know how to make it so if you type either code in, you can proceed.
For example the text file looks like this
john123,x,x,x
susan233,x,x,x
conor,x,x,x
What i need to do is accept the name tag despite what one it is and be able to print it after. All the name tags are in one column.
file = open("paintingjobs.txt","r")
details = file.readlines()
for line in details:
estimatenum = input ("Please enter the estimate number.")
if estimatenum = line.split
This is my code so far, but i do not know what to do in terms of seeing if the name tag is valid to let the user proceed.
Here is another solution, without pickle. I'm assuming that your credentials are stored one per line. If not, you need to tell me how they are separated.
name = 'John'
code = '1234'
with open('file.txt', 'r') as file:
possible_match = [line.replace(name, '') for line in file if name in line]
authenticated = False
for item in possible_match:
if code in tmp: # Or, e.g. int(code) == int(tmp)
authenticated = True
break
You can use a module called pickle. This is a Python 3.0 internal library. In Python 2.0, it is called: cPickle; everything else is the same in both.
Be warned that the way you're doing this is not a secure approach!
from pickle import dump
credentials = {
'John': 1234,
'James': 4321,
'Julie': 6789
}
dump(credentials, open("credentials.p", "wb"))
This saves a file entitled credentials.p. You can the load this as follows:
from pickle import load
credentials = load(open("credentials.p", "rb"))
print(credentials)
Here are a couple of tests:
test_name = 'John'
test_code = 1234
This will amount to:
print('Test: ', credentials[test_name] == test_code)
which displays: {'John': 1234, 'James': 4321, 'Julie': 6789}
Displays: Test: True
test_code = 2343
print('Test:', credentials[test_name] == test_code)
Displays: Test: False

dictionary reading from module

I have following module root_file.py. This file contains number of blocks like.
Name = {
'1':'a'
'2':'b'
'3':'c'
}
In other file I am using
f1= __import__('root_file')
Now the requirement is that I have to read values a,b,c at runtime using variables like
for reading a
id=1
app=Name
print f1[app][id]
but getting error that
TypeError: unsubscriptable object
How about
import root_file as f1
id = 1
app = 'Name'
print getattr(f1, app)[id] # or f1.Name[id]
Uh, well, if I understand what you are trying to do:
In root_file.py
Name = {
'1':'a', #note the commas here!
'2':'b', #and here
'3':'c', #the last one is optional
}
Then, in the other file:
import root_file as mymodule
mydict = getattr(mymodule, "Name")
# "Name" could be very well be stored in a variable
# now mydict eqauls Name from root_file
# and you can access its properties, e.g.
mydict['2'] == 'b' # is a True statement

Categories