Retrieve the key value in the Dictionary - python

I have two loops, one to retrieve the key (Email address) and store it into a variable and another loop to retrieve the value of the keys (List containing data). However, after the script runs, the final key is repeated.
I have attempted shifting the for loops around and attempted creating a new block of code that puts the keys into a list and just retrieve them one by one, but it didn't work.
Code
import re
import os
userInfoDict = dict()
newDict = eval(open("/home/ad.ilstu.edu/keschm1/IT170/UserLog//myData.txt").read())
list = []
#print(newDict)
email = ' '
firstName = ' '
lastName = ' '
IP = ' '
for keys in newDict.keys():
email = keys
for values in newDict.values():
firstName = values[0]
lastName = values[1]
IP = values[2]
#print('The name is: ' + firstName + ' ' +lastName +' the IP is: ' + IP +'\n')
list.append(email + ": " + firstName + " " + lastName +":" + IP)
file = open("userInfo.txt", "w")
for items in list:
file.write(items + '\n')
#print(items)
file.close()
This is the result when printing onto a txt document
hosack#comcast.com.:Glen Wilson:172.39.112.76
hosack#comcast.com.:Cindy Tady:123.18.19.20 hosack#comcast.com.:Emma
Lim:11.11.11.11 hosack#comcast.com.:Anna Smith:172.28.19.15
hosack#comcast.com.:Jack Hosack:196.88.45.23

for keys in newDict.keys():
email = keys
What do you think this does? This assigns each key in newDict to the same email variable, one after another. So email will end up set to the last keys value you processed from the newDict dictionary. Probably not what you want.
Since this is the only way you set email, it will always be set to the same value when used later on in your code.
What you probably want is something like this:
for email, values in newDict.items():
firstName = values[0]
lastName = values[1]
IP = values[2]
#print('The name is: ' + firstName + ' ' +lastName +' the IP is: ' + IP +'\n')
list.append(email + ": " + firstName + " " + lastName +":" + IP)

Related

Is there a way to use fuzzywuzzy with an UpdateCursor to select features and then pass the variable with the highest ratio?

I am comparing two parcel datasets and want to use fuzzywuzzy to identify owner names that are similar. For example, City of Pittsburgh verses City of Pitt. I am currently using an UpdateCursor to do other things with the data and am not sure how I can add the fuzzy logic to this.
What I would like to do is have the script select all parcels that border the update cursor parcel, compare two fields for a fuzzy ratio, and then pass the variable for the one with the highest ratio.
Here is the original script that I'd like to modify with the fuzzy logic.
count = 0
with arcpy.da.UpdateCursor(children,c_field_list) as update1:
for u1row in update1:
c_owner = u1row[0]
c_id = u1row[1]
c_parent = u1row[2]
c_geo = u1row[3]
if c_parent == " ":
parents_select = arcpy.management.SelectLayerByLocation(parents, 'BOUNDARY_TOUCHES', c_geo, '', 'NEW_SELECTION')
whereClause = ' "ACCOUNTPAR" ' + " != '" + str(c_owner) + " ' "
with arcpy.da.SearchCursor(parents_select, p_field_list,whereClause) as search1:
for parent in search1:
p_owner = parent[0]
p_id = parent[1]
p_add = parent[2]
print("Parent Account Party: " + p_add + " " + p_id + " Child SOW Owner: " + c_owner + " " + c_id)
u1row[2] = p_id
u1row[4] = 6
update1.updateRow(u1row)
count += 1
print("Updating " + c_owner + " with " + u1row[2])
else:
pass
print("Aggregation Analysis Complete")
print(str(count) + " parcels updated")

How to check if an element is not in file?

How to check if an element is not in a python File, I tried:
if not element in File.read()
But the "not in" doesn't seems to work I also tried:
if element not in File.read()
Edit: Code Snippet
phone = input('Enter a new number :')
imp = phone
if phone not in phbook.read() and phone_rule.match(imp):
phbook = open('Phonebook','a')
phbook.write('Name: ' + firstname + '\n')
phbook.write('Phone: ' + phone + '\n')
if phone in phbook.read():
print('sorry the user already have this phonenumber ')
else:
if phone_rule.match(imp):
phbook = open('Phonebook','a')
phbook.write('Name: ' + firstname + '\n')
phbook.write('phone: ' + phone + '\n')
print('user added !')
else:
print('This is not a good format')
Not working either
You need to open the file before accessing it.
After reading it, the file cursor is at the end of the file.
You could use phbook.seek(0) to set the cursor at the beginning of the file.
A cleaner way would be to ensure you are using your file only once giving it a better structure, eg:
phone = input('Enter a new number :')
imp = phone
phonebook_filename = 'phonebook.txt'
def ensure_phone_in_phonebook(phone):
with open(phonebook_filename) as phbook:
if phone not in phbook.read() and phone_rule.match(imp):
add_data(firstname, phone)
def add_data(firstname, phone):
with open(phonebook_filename, 'a') as phbook:
phbook.write('Name: ' + firstname + '\n')
phbook.write('Phone: ' + phone + '\n')
ensure_phone_in_phonebook(phone)
Also note the usage of context manager statement with.
It bewares you of closing the file after using.
Further informations

list index out of range when extending list

This function takes email body as input and returns values after Application name, source and message respectively and it works fine
def parse_subject(line):
info = {}
segments = line.split(' ')
info['time'] = segments[0]+' '+segments[1]
for i in range(2, len(segments)):
key = ''
if segments[i] == 'Application name:':
key = 'appname'
elif segments[i] == 'Source:':
key = 'source'
elif segments[i] == 'Message:':
key = 'message'
if key != '':
i += 1
info[key] = segments[i]
return info
For another email body format i need to extend segments format because i need to search more lines in message body so i changed info['time'] and as soon i extend segments for more than 2 i'm getting out of range errors
info['time'] = segments[0]+' '+segments[1]+' '+segments[2]+' '+segments[3]+' '+segments[4]+' '+segments[5]......up to segment[17]
maybe i'll need to extend more
and above function fails with list index out of range
i changed code but same error:
also tried changing number to match number of segments but same:
for i in range(<number of segments>, len(segments)):
example of segments: lenght will vary because string after Message has different value, sometime it's URL string
Question
when i define lenght of the segment, let's say up to segments[17],
what i need to change in function not to throw out of index error
def parse_subject(line):
info = {}
segments = line.split(' ')
info['time'] = segments[0]+' '+segments[1] + ' ' + segments[2] + ' ' + segments[3] + ' ' + segments[4] + ' ' + segments[5] + ' ' + segments[6] + ' ' + segments[7] + ' ' + segments[8] +' ' + segments[9] + ' ' + segments[10] + ' ' + segments[11] + ' ' + segments[12] +' ' + segments[13] + ' ' + segments[14] + ' '
+ segments[15] +' ' + segments[16] + ' ' + segments[17]
for i in range(16, len(segments)):
key = ''
if segments[i] == 'name:':
key = 'appname'
elif segments[i] == 'Source:':
key = 'source'
elif segments[i] == 'Message:':
key = 'message'
if key != '':
i += 1
info[key] = segments[i]
return info
if mail["Subject"].find("PA1") > 0 or mail["Subject"].find("PA2") > 0:
body = get_autosys_body(mail)
# print(body)
for line in body.splitlines():
if 'Application Name' in line:
job_info = parse_subject(line)
break
print(job_info)
I need to pass line variable (content below)
name:Contoso.Service
Source: host15
Timestamp: 2019-01-22T00:00:43.901Z
Message:null
to parse_subject(line) function and from above output to get:
Contoso.Service as value of job_info['appname']
host15 as value of jobinfo['source']
null as value of jobinfo['message']
In your code, you need to debug it. The error is telling you exactly what is wrong.
def old_parse_subject(line):
info = {}
segments = line.split(' ')
if len(segments < 18):
raise ValueError("segments[17] won't work if segments is not that long")
You could have done a print(len(segments)) or just print (segments) right before where you know the error is.
For reading an email header, if you know it has multiple lines, you get those with split('\n') and then for each line if you know it is "name: value" you get that with split(':', 1).
The second argument to split says only split on 1 colon, because any additional colons are allowed to be part of the data. For example, timestamps have colons.
def parse_subject(headers):
info = {}
# split the full header into separate lines
for line in headers.split('\n'):
# split on colon, but only once
key, value = line.split(':', 1)
# store info
info[key] = value
return info
data = """name:Contoso.Service
Source: host15
Timestamp: 2019-01-22T00:00:43.901Z
Message:null"""
print (parse_subject(data))
{'name': 'Contoso.Service', 'Source': ' host15', 'Timestamp': ' 2019-01-22T00:00:43.901Z', 'Message': 'null'}

How would I print the fav_genre field for a specific user

So the code below saves the variables username pass etc into a text file with the colons to separate each field. say I wanted to print out the favourite genre of a particular user, how would that be possible as my attempts so far to do so have failed. this is all in python btw. ive edited to add my attempt but its not woking.Any ideas??
usrFile_write = open(textfile, 'a')
usrFile_write.write(username + ' : ' + password + ' : ' + name + ' : ' + dob + ' : ' + fav_artist + ' : ' + fav_genre + ' : ' + '\n')
print('New Account Created!')
print()
usrFile_write.close()
Menu()
my attempt:
textfile = 'user_DB.txt'
username = 'dj'
def getUsersFavouriteGenre():
with open(textfile, 'r') as textIn:
for line in textIn:
information = line.split(' : ')
if information[0] == username:
return information[5]
return 'Failed to find user.'
getUsersFavouriteGenre()
Your code looks good. I'm assuming the issue is your program doesn't output anything, in which case the only issue I see is change your last line getUsersFavouriteGenre() to print(getUsersFavouriteGenre())
If you are getting a specific error or undesired output then you can let us know and we can help you more specifically.

Trying to pull specific values from a database

I have an sqlite3 table in python that looks like this:
CREATE TABLE words
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
CURRENT_WORD TEXT NOT NULL,
BEFORE_WORD TEXT NOT NULL,
AFTER_WORD TEXT NOT NULL,
OCCURANCES INTEGER NOT NULL)
It returns the following database values:
(1, u'is', u'This', u'true', 0)
(2, u'you', u'are', u'ready', 1)
I'd like to be able to pull the value 'OCCURANCES' from id 2. I've tried the following, I was then planning to parse the returned value with regex, but my code doesn't appear to be working:
def db_check(db, words):
conn = sqlite3.connect(db)
c = conn.cursor()
frequency = 0
print("SELECT * FROM words WHERE CURRENT_WORD = '" + words[1] + "' AND BEFORE_WORD = '" + words[0] + "' AND AFTER_WORD = '" + words[2] + "'")
for row in c.execute("SELECT * FROM words WHERE CURRENT_WORD = '" + words[1] + "' AND BEFORE_WORD = '" + words[0] + "' AND AFTER_WORD = '" + words[2] + "'"):
print "FOUND: "
print row
conn.commit()
if frequency == 0: frequency = 1
return frequency
Any idea where I'm going wrong? I'd say it's wrong with my SQL in the last part. Is there a better way to do this, such as pulling the frequency exactly?

Categories