Convert a multi value dictionary to a Dataframe in python - python

The dictionary
{'password': ['Input data fields to enter - 1) Username 2) Password 3) Re-enter Password 4) Security question 5) Security answer\nUsername data field specifications - At least one uppercase, \nUsername data field specifications - At least one lowercase.',
'Password data field specifications - At least 7 characters, \nPassword data field specifications - 1 number, \nPassword data field specifications - 1 uppercase letter, \nPassword data field specifications - 1 lowercase letter, \nPassword data field specifications - one special charactersss.',
'Password criteria should be displayed to the user when user clicks inside the password data field.',
"Green check mark next to 'Password' data field should be displayed that indicates to the user after typing password that the entry meets criteria.",
"Red cross mark next to 'Password' data field should be displayed that indicates to the user after typing password that the entry does not meet criteria.",
"Validate that inputs in 'Password' and 'Re-enter Password' data fields match- Green check mark next to 'Re-enter' password data field should be displayed that indicates to the user after typing if passwords match\n'Password' and 'Re-enter Password' entries should be masked.",
'Password entries will show the keystroke typed, and then after two seconds the entered character is masked.',
'If \'Password\' entry does not match criteria specified and user hits Submit, show error alert "Password entry does not meet criteria".',
"If entries in 'Password' and 'Re-enter Password' do not match and user hits Submit, show error alert 'Password entries do not match'."]}
Needed to a data-frame by converting these list of values into a DF with same key

I am not really sure about what you want but
import pandas as pd
dataframe = pd.DataFrame('Your dictionary comes here')
Additionally:
If you have just an array and you need to put it into a dataframe
import pandas as pd
dataframe = pd.DataFrame() # Without any arguments
dataframe['The Coulmn name'] = 'Your array comes here'

I am not sure about your desired out put, may be you wanted something like this.
import pandas as pd
df = pd.DataFrame({'password': ['Input data fields to enter - 1) Username 2) Password 3) Re-enter Password 4) Security question 5) Security answer\nUsername data field specifications - At least one uppercase, \nUsername data field specifications - At least one lowercase.',
'Password data field specifications - At least 7 characters, \nPassword data field specifications - 1 number, \nPassword data field specifications - 1 uppercase letter, \nPassword data field specifications - 1 lowercase letter, \nPassword data field specifications - one special charactersss.',
'Password criteria should be displayed to the user when user clicks inside the password data field.',
"Green check mark next to 'Password' data field should be displayed that indicates to the user after typing password that the entry meets criteria.",
"Red cross mark next to 'Password' data field should be displayed that indicates to the user after typing password that the entry does not meet criteria.",
"Validate that inputs in 'Password' and 'Re-enter Password' data fields match- Green check mark next to 'Re-enter' password data field should be displayed that indicates to the user after typing if passwords match\n'Password' and 'Re-enter Password' entries should be masked.",
'Password entries will show the keystroke typed, and then after two seconds the entered character is masked.',
'If \'Password\' entry does not match criteria specified and user hits Submit, show error alert "Password entry does not meet criteria".',
"If entries in 'Password' and 'Re-enter Password' do not match and user hits Submit, show error alert 'Password entries do not match'."]})
print df
Output:
password
0 Input data fields to enter - 1) Username 2) Pa...
1 Password data field specifications - At least ...
2 Password criteria should be displayed to the u...
3 Green check mark next to 'Password' data field...
4 Red cross mark next to 'Password' data field s...
5 Validate that inputs in 'Password' and 'Re-ent...
6 Password entries will show the keystroke typed...
7 If 'Password' entry does not match criteria sp...
8 If entries in 'Password' and 'Re-enter Passwor

Related

How can I show randomly different data for each user in Django?

I have a tag system in Django with the following model;
class Data(models.Model):
new = models.ChardField()
is_tagged = models.BooleanField(default=False)
class Tag(models.Model):
data = models.ForeignKey(Data,on_delete=models.CASCADE,related_name="data")
status = models.CharField(verbose_name="New Status",max_length=10,null=True)
The tag status holds "positive", "negative", and "pass".
There is a page called "new tags" and around 100 users will enter the page at the same time.
There are 10000 data and users will enter the page and just click "positive", "negative", and "pass".
I want to show different data for each user.
EDIT
New1: id = 1,is_tagged=False
New2: id = 2,is_tagged=False
User 1: Display New1
User 2: Display New1
User 1: Tag: "Positive" and id = 1, is_tagged will be "True"
Because both user open the windows at the same time, after 1 second,
User 2: Tag: "Pass" and id = 1 , is_tagged will be "False"
I want to prevent this situation. It supposed to be;
User 1: Display New1
User 2: Display New2
So each user must display different News Data to tag.
Let's say a user tagged the new as "positive". If I will send the new with random() it can be the same at another user unluckily. And the user can tag as "pass". This status will make "Data" "is_tagged" False. But other users tagged "positive" before.
How can I prevent users see the same data at the same time?
If you need to get a random object, you could do something like:
import random
all_object_ids = Data.objects.all().values_list('id', flat=True) # gets list of all object ids
random_id = random.choice(all_object_ids) # picks a random id from list
random_tag = Data.objects.get(id=random_id)

I don't understand why I get a "too many values to unpack" error

When I run this I can get it to ask me for my password but when it start my "for" loop, I get a error regrading my data.
import csv, smtplib, ssl
import pandas as pd
newhire = pd.read_csv('New_Hires_Test.csv', delimiter = ",", skiprows=7) #Open up the document and
skip header
newhire["Email"] = "test#gmail.com" #Add a row 'Email' and add email address
mask = newhire["New IT Item"] == "New" #brings back only new in "New IT Item column"
message = """\Subject: {Effective Date}
From: test#gmail.com
To: test#gmail.com
Hello IT,
We have a new user by the name of {StartDate}. The new user will be starting on {Employee} and will
be working at {PC}.
Their title will be {Title} and their supervisor is {Supervisor}"""
from_address = "test#gmail.com"
password = input("Type your password and press enter: ")
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(from_address, password)
for Employee, StartDate, PC, Title, Supervisor, Email in newhire[mask]:
server.sendmail(
from_address,
Email,
message.format(Employee=Employee, StartDate=StartDate, PC=PC, Title=Title, Email=Email,
Supervisor=Supervisor)
)
print('Emails were sent successfully!')
***ValueError: too many values to unpack (expected 6)***
I'm looking at my "for" loop and I see that have 6 columns that I am looking for. My data is all strings and I set up a delimiter just to make sure that all of the data is separated properly.I think I am just either overlooking the issue or not understanding my data.
****New_Hires_Test.csv***
Report: ,,,All HR Action Requests: IT CAFs - New Hires (KB
Copy),,,,,,,,,,,,,
Sorted By: ,,,Effective Date Descending,,,,,,,,,,,,,
Filtered By: ,,,Initiator Filter: All Employees; Employee Filter: All
Employees; Approver Filter: All Employees; HR Action = Hire Employee (Staff)
- Step 2,,,,,,,,,,,,,
Date & Time: ,,,01/06/2020 09:12p,,,,,,,,,,,,,
Generated By: ,,,Haywood,,,,,,,,,,,,,
Company: ,,,Corp Solutions(6122261),,,,,,,,,,,,,
,,,,,,,,,,,,,,,,
New IT Item,StartDate,Effective Date,Employee Name,PC,Title,Supervisor
Name,Manager 2 Name,O365,ID
Badge,Computer,Avionte,GP,Hotspot,Tablet,TimeZone,HR Action
New,01/13/2020,02/03/2020,Elizabeth Anne Everts,Internal Staff/003 -
003,Onboarding Specialist,Suzanne Mitchell,Angela
Robbins,Yes,,No,Yes,No,No,No,Eastern,Hire Employee (Staff) - Step 2
New,01/13/2020,01/13/2020,Karla Ramirez,Internal Staff/204 - 003,
Recruiter,Scott Clark,Shane Houser,Yes,,Standard
Laptop,Yes,Yes,No,No,Central,Hire Employee (Staff) - Step 2
New,01/13/2020,01/06/2020,Megan Arreola,Internal Staff/221 -
003,Recruiter,Elsa Muneton,Amanda Stewart,Yes,,No,Yes,No,No,No,Eastern,Hire
Employee (Staff) - Step 2
Replace you for loop with iterrows() call as below:
for i, r in newhire[mask].iterrows():
server.sendmail(
from_address,
r["Email"],
message.format(Employee=r["Employee"],
StartDate=r["StartDate"],
PC=r["PC"],
Title=r["Title"],
Email=r["Email"],
Supervisor=r["Supervisor"]
)
)
EDIT1:
newhire[mask] in for a,....,c in newhire[mask] will unpack the contents of newhire[mask] int a,....,c ( the whole dataframe ). What you want to do is unpack the contents of only a single row. In order to do that you can use newhire[mask].iterrows() which, on every row returns its index and the row instance itself.
You can also use itertuples() as described in this question Pandas for loop over dataframe gives too many values to unpack

How to call and iterate through specific indexes of a dictionary?

I currently have code that prints out a username and their password by means of dictionary. The output is username:abc password:12345. Right now I have them all just printing out at the same time. My main goal is to be able to email these users based on their usernames, but of course I only want to include their username and password information. Not the whole list of information. So basically I want to be able to tell the specific user only their password. For example, I would want to send an email to user abc and that email should only contain their username and password. Then I would like to send an email to user xyz but that should only contain the password of user xyz. Is there a way I can make this happen?
I currently have everything from the dictionary printing. So all the usernames and passwords are being printed out. How can I iterate through these and send an email to each user with their password?
lines = []
User_Pass = {}
#Open output file and show only lines that contain 'Success'
with open("output.txt", "r") as f:
for line in f.readlines():
#Get rid of everything in line after 'Success'
if 'Success' in line:
lines.append(line[:line.find("Success")-1])
for element in lines:
parts = element.strip().split(":")
User_Pass.update({parts[0] : parts[1]})
for key, value in User_pass.items():
print('Username: ' + key + ' Password: ' + value)
I want to be able to email each username and tell them their password. I am really not sure how to go about this. Any help would be appreciated!
Assuming you have the dictionary constructed, you just ask it for the value associated with the key, which is the username:
user_pw = User_Pass.get(username)
this will return None if the username is not in the dictionary.
Suggest you research Python dictionaries for some examples. In your loop code, you have it a little backwards as well. Anytime you want to iterate through a dictionary (the right way) you want to do it with the keys, not the items, so to loop through all in your example:
for key in User_Pass.keys():
print (key, User_Pass.get(key) )
Only fill your User_Pass dictionary when you meet "username" or "password":
for element in lines:
key, value = element.strip().split(":")
if key in {"username", "password"}:
User_Pass.update({key: value})
A simple demonstration:
lines = [
"fullname:John Doe",
"username:jdoe",
"password:S3cRet",
"age:45",
]
User_Pass = {}
for element in lines:
key, value = element.strip().split(":")
if key in {"username", "password"}:
User_Pass.update({key: value})
print(User_Pass)
You get:
{'username': 'jdoe', 'password': 'S3cRet'}
Please, you should follow the naming conventions of the PEP8: "User_Pass" => "user_pass".

While loop in python showing value of next word while reading a file

I have made a selenium based python program which inserts some data and if a particular set of input is right it returns it value but if the correct value is let suppose 2 then its giving the very next line as its output like 3
i am inserting values in a web form using selenium and if the login details are right it should return me with the login details (its my own Webform )which in this case is username from 1-10 but if the details match for username 2 its again reading the file and showing it was found for username 3 .
f = open('a.txt', 'r')
line=f.readline().strip()
while line :
line=f.readline().strip()
print 'inserting username' , line
if ('Profile Information' in driver.page_source):
count = 1
print 'username is ' , line
break
if ('An error occurred while processing your request.' in driver.page_source):
print 'LookS like server time out or webpage has been inserted with a character waiting for 10 sec'
time.sleep(10)
driver.get(url)
driver.find_element_by_id("Fno").clear()
driver.find_element_by_id("Fno").send_keys('18047476')
driver.find_element_by_id("DOB").clear()
driver.find_element_by_id("DOB").send_keys(line)
driver.find_element_by_link_text("Login").click()
here is the output
insering username 1
insering username 2
username is = 3

Web2py linked tables error with Field type

I am trying to link two mysql tables in web2py which have a column with identical entries (different rows though). I want to display the first table in a grid and have a link that displays the appropriate entries of the second table. So far this is what i have:
in models --> db.py
db.define_table('total_ec_numbers',
Field('id','integer', label=T('ID')),
Field('query_name','string', label=T('Gene ID')),
Field('hit_name','string', label=T('Hit name')),
Field('hit_accession','string', label=T('Hit accession')),
Field('ec','string', label=T('EC number')),
Field('hsp_evalue','string', label=T('E-value')),
Field('hsp_length','string', label=T('HSP length')),
Field('hsp_percent','string', label=T('HSP percent')),
Field('sample','string', label=T('Sample')),
Field('extra','string', label=T('Extra info')),
migrate=False, format = '%(query_name)s')
db.total_ec_numbers._singular = "EC numbers results"
db.total_ec_numbers._plural = "EC numbers results"
#--------
db.define_table('total_genes',
Field('id','integer', label=T('id')),
Field('gene_id','string', label=T('Contig')),
Field('gene_name','string', label=T('Gene name')),
Field('sequence','text', label=T('Sequence')),
Field('seq_length','integer', label=T('Sequence length')),
Field('description', 'reference total_ec_numbers', label=T('Gene ID')),
Field('sample','string', label=T('Sample')),
Field('extra','string', label=T('Extra info')),
migrate=False)
db.total_genes._singular = "All sequences"
db.total_genes._plural = "All sequences"
in controllers --> default.py
important_columns=[db.total_ec_numbers.query_name,db.total_ec_numbers.hit_name,db.total_genes.description]
form2=SQLFORM.smartgrid(hotzyme_tests.total_ec_numbers, linked_tables=['total_genes'], create=False, fields=important_columns, deletable=False, editable=False, maxtextlength=64, paginate=10)
with this i get a nice grid of the "total_ec_numbers" table with the link "all sequences" next to each entry. But when i click on the link i get the following error:
ValueError: invalid literal for int() with base 10: '1_start=553_stop=756_strand=+'
The fields that have the identical entries are the db.total_ec_numbers.query_name and the db.total_genes.description and they have string data values. Nevertheless web2py seems to search for integers. Do you know how i can change that? Thank you in advance,

Categories