I saved some dictionaries in a .txt with:
# The form of store the data is in a dictionary of a dictionary
data = { "DNI": dni, "Nombre": name, "Apellido": surname, "Usuario": username, "ContraseƱa": password}
with open(dbUsers, "a+") as db:
db.write("\n" + str(data))
# Finally the program send a OK message and close the file
db.close()
print("El usuario y sus datos se han introducido correctamente.")
Now I'm trying to get the different lines (one line, one dictionary) of the .txt with:
with open(dbUsers, "r") as db:
for line in db:
But that lines are not a dictionary so I can't get the different values with the keys. My question is: how can I convert the different lines (with a dictionary format) with a dictionary inside in python?
You can use ast.literal_eval to convert the string to a dict.
import ast
with open(dbUsers, "r") as db:
for line in db:
if not line.isspace():
d = ast.literal_eval(line)
print(d)
Related
users = {
"Hi":"HM123",
"alan": "12122",
"12": "11"
}
def adder():
new_user = input("Please enter user's name: ").strip()
new_pwd = ""
confirmer = "0"
while new_pwd != confirmer:
new_pwd = input("please enter a new Password: ").strip()
confirmer = input("please confirm your password: ").strip()
if new_pwd != confirmer:
print("passwords does not match!!")
users[new_user] = new_pwd
adder()
I used The dictionary as a collection of usernames and passwords to practice creating a simple functional login page.(i'm importing this as a module to my main file). and when I add new users and passwords this code above temporarily adds it to the dictionary but when I re-run the script and try the new user names and pwds it returns incorect username and password, bc they are not in the dictionary.
was hoping to find a way to add the new usernames and paswwords into the dictionary permanently just with user inputs without having to modify the dictionary my self.
Your dictionary (more or less) is stored in RAM which is voilatile - you cannot (or at least, you shouldn't try to) preserve it between different scripts run.
Thas is why people use databases - they are stored on disk and don't vanish unless something really bad happens ;)
The easiest what would suits your needs is to store them in a single json file. It is a format very similar to python dictionary. Python has json library that allows it to parse such file into pythons dict and the opposite - put the dict back into the file.
Here is the example:
import json
with open("users.json", "r+") as f:
# convert content of file users.json into users variable - it will be a dict
users = json.load(f)
def store_to_file(users):
with open("users.json", "w") as f:
# save the users dict into the file users.json in json format
json.dump(users, f, indent=4)
def adder():
...
store_to_file(users)
adder()
Do not forget to create the file users.json!
{
"Hi": "HM123",
"alan": "12122",
"12": "11"
}
Python dictionaries can be converted to JSON text and written to permanent storage as such.
You could also consider serialisation of the dictionary using the pickle module.
Here's an example of both techniques:
import pickle
import json
PFILE = '/Volumes/G-Drive/users.pkl'
JFILE = '/Volumes/G-Drive/users.json'
users = {
"Hi": "HM123",
"alan": "12122",
"12": "11"
}
with open(PFILE, 'wb') as db:
pickle.dump(users, db) # save the dictionary (serialise)
with open(PFILE, 'rb') as db:
_users = pickle.load(db) # retrieve serialised data
print(_users)
with open(JFILE, 'w') as db:
json.dump(users, db) # save as JSON
with open(JFILE) as db:
_users = json.load(db) # retrieve JSON and convert to Python dictionary
print(_users)
Output:
{'Hi': 'HM123', 'alan': '12122', '12': '11'}
{'Hi': 'HM123', 'alan': '12122', '12': '11'}
let's assume that program take these variables;
website = "https://stackoverflow.com/questions/"
username = "BestSithInEU"
password = "S0n'X%`2FU`,t!j-"
My aim that, I want to store these datas with another class;
class forExample:
self.header = ["website", "username / email", "password"]
self.data_list = [website, username, password]
### And I'm using this method from csv library
with open("password.csv", "a", encoding="UTF8", newline="") as f:
writer = csv.writer(f)
write multiple rows
writer.writerows(self.data_list)
How can I convert these three variables to list of strings? And also when I use this self.data_list I'm getting this output...
website
username/email
password
h,t,t,p,s,:,/,/,s,t,a,c,k,o,v,e,r,f,l,o,w,.,c,o,m,/,q,u,e,s,t,i,o,n,s,/
B,e,s,t,S,i,t,h,I,n,E,U
_csv.Error: iterable expected, not NoneType
The csv writer expects a list of lists. So
self.data_list = [ [website, username, password] ]
I have this txt file but I'm having trouble in converting it into a nested dictionary in python. The txt file only has the values of the pokemon but are missing the keys such as 'quantity' or 'fee'. Below is the content in the txt file. (I have the ability to change the txt file if needed)
charmander,3,100,fire
squirtle,2,50,water
bulbasaur,5,25,grass
gyrados,1,1000,water flying
This is my desired dictionary:
pokemon = {
'charmander':{'quantity':3,'fee':100,'powers':['fire']},
'squirtle':{'quantity':2,'fee':50,'powers':['water']},
'bulbasaur':{'quantity':5,'fee':25,'powers':['grass']},
'gyrados':{'quantity':1,'fee':1000,'powers':['water','flying']}
}
Convert text file to lines, then process each line using "," delimiters. For powers, split the string again using " " delimiter. Then just package each extracted piece of information into your dict structure as below.
with open('pokemonInfo.txt') as f:
data = f.readlines()
dict = {}
for r in data:
fields = r.split(",")
pName = fields[0]
qty = fields[1]
fee = fields[2]
powers = fields[3]
dict[pName] = {"quantity": qty, "fee": fee, "powers": [p.strip() for p in powers.split(" ")]}
for record in dict.items():
print(record)
i have a csv file with a header, and two lines with values, like this:
Csv File
And i have a dictionary in python like this:
Python dictionary
All the fields in the csv file are of string type. And i want some of those fields to become Integer. So what i want to do is, to compare the fields in csv to the dictionary, and then check every field from my dictionary, and where it says "Int", i want to convert those fields from the csv to Int. Haven't been able to do it with this current code:
try:
with open('Book1.csv', newline='') as csvFile:
reader = csv.reader(csvFile)
filedictreader = csv.DictReader(csvFile, delimiter=',')
print(type(filedictreader))
for element in filedictreader:
for key in element:
print(key)
except Exception as e:
print("Error: " + str(e))
Output:
<class 'csv.DictReader'>
Site_ID
Site_Name
Site_Type
Latitude
Longitude
Address
Supplier
Access_Details
Access_Time
Telephone_Number
County
Battery_Hours
Cir_ID
Cir_Type
Cir_Capacity
Cir_Owner
Site_A
Site_B
Cust_Name
Redundancy
Site_A_Node
SiteA_Int
SA_Dish_Height
SA_Dish_Azm
SiteA_size
Site_B_Node
SiteB_Int
SiteB_size
SB_Dish_Height
SB_Dish_Azm
Node_ID
Node_Name
Node_IP
Node_Type
Node_Vendor
Node_Model
Location
Site_ID
Site_Name
Site_Type
Latitude
Longitude
Address
Supplier
Access_Details
Access_Time
Telephone_Number
County
Battery_Hours
Cir_ID
Cir_Type
Cir_Capacity
Cir_Owner
Site_A
Site_B
Cust_Name
Redundancy
Site_A_Node
SiteA_Int
SA_Dish_Height
SA_Dish_Azm
SiteA_size
Site_B_Node
SiteB_Int
SiteB_size
SB_Dish_Height
SB_Dish_Azm
Node_ID
Node_Name
Node_IP
Node_Type
Node_Vendor
Node_Model
Location
See my comment to your question. Here I am showing how you can test each column type and convert the value if it is supposed to be an integer. But as I commented, I don't know what you want to do with it after the conversion. And since you did not provide the dict1 dictionary in any form that could be copied and pasted (and I was not about type the complete declaration myself, I have only defined one entry for demo purposes).
I have removed the reader variable, which is not used and renamed some variables to what for me seems more logical names and to follow the PEP 8 -- Style Guide for Python Code for naming varibles.
import csv
dict1 = {
"Site_Name": "String"
}
try:
with open('Book1.csv', newline='') as csv_file:
dictreader = csv.DictReader(csv_file, delimiter=',')
for row in dictreader:
for field_name in row:
if dict1.get(field_name, 'String') == 'Int':
# conversion (can throw an exception):
row[field_name] = int(row[field_name])
except Exception as e:
print("Error:", e)
I am trying to find a way to parse a JSON string and save them into mysql.
This is my json!
{"title": My title, "desc": mydesc, "url": http//example.com}
From now i don't have problem to save all json into one column usining json.dumps() so actually I'm trying to parse each joson data string to send him to mysql table. Title | Desc | Url.
This is my python code for desc example (pyspider-resultdb.py)
def _parse(self, data):
for key, value in list(six.iteritems(data)):
if isinstance(value, (bytearray, six.binary_type)):
data[key] = utils.text(value)
if 'result' in data:
decoded = json.loads(data['result'])
data['result'] = json.dumps(decoded['desc'])
return data
def _stringify(self, data):
if 'result' in data:
decoded = json.loads(data['result'])
data['result'] = json.dumps(decoded['desc'])
return data
It's unclear from your question what you trying to achieve, but If your question is how to convert JSON to python dict and then load to the table, then that's how you can do it:
my_dict = json.loads('{"title": "foo", "dest": "bar"}')
curs.execute('INSERT INTO test (title, dest) values(%(title)s, %(dest)s)', my_dict)