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.
Related
I have this Python code:
with open('save.data') as fp:
save_data = dict([line.split(' = ') for line in fp.read().splitlines()])
with open('brute.txt') as fp:
brute = fp.read().splitlines()
for username, password in save_data.items():
if username in brute:
break
else:
print("didn't find the username")
Here is a quick explanation; the save.data is a file that contains variables of Batch-file game (such as username, hp etc...) and brute.txt is a file that contains "random" strings (like what seen in wordlists used for brute-force).
save.data:
username1 = PlayerName
password1 = PlayerPass
hp = 100
As i said before, it's a Batch-file game so, no need to quote strings
brute.txt:
username
usrnm
username1
password
password1
health
hp
So, let's assume that the Python file is a "game hacker" that "brute" a Batch-file's game save file in hope of finding matches and when it does find, it retrieves them and display them to the user.
## We did all the previous code
...
>>> print(save_data["username1"])
PlayerName
Success! we retrieved the variables! But I want to make the program capable of displaying the variables it self (because I knew that "username1" was the match, that's why I chose to print it). What I mean is, I want to make the program print the variables that matched. E.g: If instead of "username1" in save.data there was "usrnm", it will surely get recognized after the "bruting" process because it's already in brute.txt. So, how to make the program print what matched? because I don't know if it's "username" or "username1" etc... The program does :p (of course without opening save.data) And of course that doesn't mean the program will search only for the username, it's a game and there should be other variables like gold/coins, hp etc... If you didn't understand something, kindly comment it and I will clear it up, and thanks for your time!
Use a dict such as this:
with open('brute.txt', 'r') as f:
# First get all the brute file stuff
lookup_dic = {word.strip(): None for word in f.readlines()}
with open('save.data', 'r') as f:
# Update that dict with the stuff from the save.data
lines = (line.strip().split(' = ') for line in f.readlines())
for lookup, val in lines:
if lookup in lookup_dic:
print(f"{lookup} matched and its value is {val}")
lookup_dic[lookup] = val
# Now you have a complete lookup table.
print(lookup_dic)
print(lookup_dic['hp'])
Output:
username1 matched and its value is PlayerName
password1 matched and its value is PlayerPass
hp matched and its value is 100
{'username': None, 'usrnm': None, 'username1': 'PlayerName', 'password': None, 'password1': 'PlayerPass','health': None, 'hp': '100'}
100
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
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
I'm writing a python scraper code for OpenData and I have one question about : how to check if all values aren't filled in site and if it is null change value to null.
My scraper is here.
Currently I'm working on it to optimalize.
My variables now look like:
evcisloval = soup.find_all('td')[3].text.strip()
prinalezival = soup.find_all('td')[5].text.strip()
popisfaplnenia = soup.find_all('td')[7].text.replace('\"', '')
hodnotafaplnenia = soup.find_all('td')[9].text[:-1].replace(",", ".").replace(" ", "")
datumdfa = soup.find_all('td')[11].text
datumzfa = soup.find_all('td')[13].text
formazaplatenia = soup.find_all('td')[15].text
obchmenonazov = soup.find_all('td')[17].text
sidlofirmy = soup.find_all('td')[19].text
pravnaforma = soup.find_all('td')[21].text
sudregistracie = soup.find_all('td')[23].text
ico = soup.find_all('td')[25].text
dic = soup.find_all('td')[27].text
cislouctu = soup.find_all('td')[29].text
And Output :
scraperwiki.sqlite.save(unique_keys=["invoice_id"],
data={ "invoice_id":number,
"invoice_price":hodnotafaplnenia,
"evidence_no":evcisloval,
"paired_with":prinalezival,
"invoice_desc":popisfaplnenia,
"date_received":datumdfa,
"date_payment":datumzfa,
"pay_form":formazaplatenia,
"trade_name":obchmenonazov,
"trade_form":pravnaforma,
"company_location":sidlofirmy,
"court":sudregistracie,
"ico":ico,
"dic":dic,
"accout_no":cislouctu,
"invoice_attachment":urlfa,
"invoice_url":url})
I googled it but without success.
First, write a configuration dict of your variables in the form:
conf = {'evidence_no': (3, str.strip),
'trade_form': (21, None),
...}
i.e. key is the output key, value is a tuple of id from soup.find_all('td') and of an optional function that has to be applied to the result, None otherwise. You don't need those Slavic variable names that may confuse other SO members.
Then iterate over conf and fill the data dict.
Also, run soup.find_all('td') before the loop.
tds = soup.find_all('td')
data = {}
for name, (num, func) in conf.iteritems():
text = tds[num].text
# replace text with None or "NULL" or whatever if needed
...
if func is None:
data[name] = text
else:
data[name] = func(text)
This will remove a lot of duplicated code. Easier to maintain.
Also, I am not sure the strings "NULL" are the best way to write missing data. Doesn't sqlite support Python's real None objects?
Just read your attached link, and it seems what you want is
evcisloval = soup.find_all('td')[3].text.strip() or "NULL"
But be careful. You should only do this with strings. If the part before or is either empty or False or None, or 0, they will all be replaced with "NULL"
If I were to search for a particular field in a mongodb collection my command would look something like this :
db.collection.find({ name : "John"})
If I want to make the field name dynamic, what would the command be?
Example:
db.collection.find({ <Dyanmic field variable> : <Value>})
Or is there an alternative to achieve this function?
Just use the variable in place of the dictionary key:
name = 'field_name'
db.collection.find({name : "John"})
Problem happens when you try without knowing data type. So in order to handle this , i used the following:
def multi_row_single_field_update(self, crieteriafldnm, crieteriafldtyp, updtfldnm, updtfldval, updtfldtyp):
try:
criteria = raw_input('\nEnter ' + crieteriafldnm + ' to update\n')
if crieteriafldtyp == 'int':
count = self.my_connect.find({str(crieteriafldnm): int(criteria)}).count()
else:
count = self.my_connect.find({str(crieteriafldnm): str(criteria)}).count()
updt_criteria = int(criteria) if updtfldtyp == 'int' else str(criteria)
self.my_connect.update(
{"$atomic": 1},
{str(crieteriafldnm): updt_criteria},
{"$set": {str(updtfldnm): str(updtfldval)}},
upsert=False, multi=True
)