So, I have been working on this simple Python program to get familiar with dictionaries. Basically, it works as a database which you can search in. If your entry is in the dictionary key, it brings up the information regarding the entry.
Family = {'Jim' : ['cool guy', 'has facial hair'],
'Ned' : ['hot stuff', ' wears Tees']}
query = input("Look up database on whom? > ")
for (name, info) in Family.items():
if name in query or name.lower() in query:
print("{} is {}".format(name, info))
This ^ works. However, when I tried to add an ELSE clause, to deal with non-existent entries, I get this.
else:
print ('Value not found!')
It prints the Value not found! many times before bringing up the value. If I try to add a 'go back to start' function it doesn't even bring up a registered value. I know this is because it is a loop and iterates over the dict one by one; so like 1)jim is true then 2) ned is false.
How do I improve this code to make it: -able to give an error about a non-existent entry and then restart the program. Thanks.
You will need to take care of case insensitivity in your code. Iterate through the list to ensure that the name exists before continuing:
Family = {'Jim' : ['cool guy', 'has facial hair'],
'Ned' : ['hot stuff', ' wears Tees']}
names = [name.lower() for name in Family]
def find(query):
if query.lower() in names:
info = [Family[n] for n in Family if n.lower() == query.lower()]
print('{} is {}'.format(
query, info
))
else:
print('{} not found'.format(query))
If you try it with the following sample:
find('Ned')
find('ned')
find('no ned')
You will get the following results:
Ned is [['hot stuff', ' wears Tees']]
ned is [['hot stuff', ' wears Tees']]
no ned not found
This is one way to do it:
Family = {'Jim' : ['cool guy', 'has facial hair'],
'Ned' : ['hot stuff', ' wears Tees']}
query = input("Look up database on whom? > ")
if query in Family.keys():
for (name, info) in Family.items():
if name in query or name.lower() in query:
print("{} is {}".format(name, info))
else:
print "Print Something - Not in Family"
Related
I'm struggling a bit on a dictionary code in Python (mind I'm a new student without any earlier experience). The strings in this code is on Norwegian, hopefully that's not a problem. The code goes as follow
participants_and_allergens = {"Ole":["gluten", "egg"],
"Silje":["shellfish", "nuts"],
"Ragnar":["milk", "fish"]}
print(participants_and_allergens.keys())
allergens_and_foods = {"Garlic bread": ["gluten", "egg"],
"Fish soup": ["shellfish", "fish"],
"Chocolate Cake": ["milk", "egg"]}
def write_name():
name = input("What is your name?\n> ")#confirms the registration of the participant
if not participants_og_allergener.get(name):
print("Sorry,", name + " does not exist in the registry")
else:
print(name + " is registered and now confirmed")
print(allergens)
print(name + " has the allergens", allergens)
allergens = participants_og_allergener.get(name)
allergens_foods = allergens_and_foods.get("allergens")
print(allergens_foods)
write_name()
Essentially, what I'm asking is, is there any way to connect to dictionaries, which are independent? When the user enters a name, it should result in values linked to the name coming out, and elements from another dictionary.
I have realized I'll have to use a for loop, but I don't know how.
The expected output should be something like "Hi Ole, you have allergies to gluten and eggs and should stay away from the foods garlic bread and chocolate cake"
I've recently just started learning Python and usally find answers to my problems online but can't seem to get the right solution for this one.
I created a dictionary with 3 contacts and i want to print 1 contact from the list using an if statement.
contacts = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
if "John" in contacts:
print ("Contact details: %s %i" % contacts.items()[0])
This is the output I am looking for:
Contact details: John 938477566
But i keep getting this
Traceback (most recent call last):
File "C:\Users\user\Documents\asega\python\objectsclasses\exercise3.py", line 31, in
print ("Contact details: %s %i" % contacts.items()[0])
TypeError: 'dict_items' object does not support indexing
Thanks
contacts.items() returns pairs of key-value. In your case, that would be something like
(("John", 938477566), ("Jack", 938377264), ("Jill", 947662781))
Except that in python 3 this is like a generator and not a list. So you'd have to do list(contacts.items()) if you wanted to index it, which explains your error message. However, even if you did list(contacts.items())[0], as discussed above, you'd get the first pair of key-value.
What you're trying to do is fetch the value of a key if said key exists and contacts.get(key, value_if_key_doesnt_exist) does that for you.
contact = 'John'
# we use 0 for the default value because it's falsy,
# but you'd have to ensure that 0 wouldn't naturally occur in your values
# or any other falsy value, for that matter.
details = contacts.get(contact, 0)
if details:
print('Contact details: {} {}'.format(contact, details))
else:
print('Contact not found')
You can do like this. If you are sure that 'John' is in the dictionary, there is no need of if statement. In other way, you can write it.. your choice
contacts = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
print("Contact details: %s %i" % ("John", contacts["John"]))
First of all its dictionary not a list , you can access the elements from a list by indexing , and it is not possible in dictionary,
you can access the elements by key
contacts = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
for k,v in contacts.items():
print(k,v)
or
contacts['John'] you can access the value
No need to check in if condition just use get to get the corresponding value and return -1 if key is not present
contacts = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
contacts.get('John',-1) # -1 will be returned if key is not found
Print formatting
name_to_search='John'
print("Contact details: %s %i" % (name_to_search, contacts.get(name_to_search,-1)))
Or
name_to_search='John'
print("Contact details: {} {}" .format(name_to_search, contacts.get(name_to_search,-1)))
Dictionaries do not support indexing so to print "John" you cant index it however the following code may word:
if "John" in contacts:
print("Contact details:","John",contacts["John"])
Hope it helps
I'm having trouble printing both the name in the list and the email. The beginning part of the code was already pre written and my attempt is the for loop. If anybody would be able to help me that would be greatly appreciated.
Here are the directions:
Write a for loop to print each contact in contact_emails. Sample output for the given program:
mike.filt#bmail.com is Mike Filt
s.reyn#email.com is Sue Reyn
narty042#nmail.com is Nate Arty
Code:
contact_emails = {
'Sue Reyn' : 's.reyn#email.com',
'Mike Filt': 'mike.filt#bmail.com',
'Nate Arty': 'narty042#nmail.com'
}
for email in contact_emails:
print('%s is %s' % (email, contact_emails(email)))
Your problem is that you need to use square brackets([]) instead of parenthesis(()). Like so:
for email in contact_emails:
print('%s is %s' % (contact_emails[email], email)) # notice the []'s
But I recommend using the .items()( that would be .iteritems() if your using Python 2.x) attribute of dicts instead:
for name, email in contact_emails.items(): # .iteritems() for Python 2.x
print('%s is %s' % (email, name))
Thanks to #PierceDarragh for mentioning that using .format() would be a better option for your string formatting. eg.
print('{} is {}'.format(email, name))
Or, as #ShadowRanger has also mentioned that taking advantage of prints variable number arguments, and formatting, would also be a good idea:
print(email, 'is', name)
A simple way to do this would be using for/in loops to loop through each key, and for each key print each key, and then each value.
Here's how I would do it:
contact_emails = {
'Sue Reyn' : 's.reyn#email.com',
'Mike Filt': 'mike.filt#bmail.com',
'Nate Arty': 'narty042#nmail.com'
}
for email in contact_emails:
print (contact_emails[email] + " is " + email)
Hope this helps.
for email in contact_emails:
print("{} is {}".format(contact_emails[email], email))
Im trying to filter few attributes from the ldap server but get errors,
ldap.FILTER_ERROR: {'desc': 'Bad search filter'}
Code:-
import ldap
ldap.OPT_REFERRALS = 0
ldap_server="ldapps.test.com"
username = "testuser"
password= "" #your password
connect = ldap.open(ldap_server)
dn='uid='+username;
print 'dn =', dn
try:
result = connect.simple_bind_s(username,password)
print 'connected == ', result
filter1 = "(|(uid=" + username + "\*))"
result = connect.search("DC=cable,DC=com,DC=com",ldap.SCOPE_SUBTREE,filter1)
print result
except ldap.INVALID_CREDENTIALS as e:
connect.unbind_s()
print "authentication error == ", e
Your search filter is, in fact, bad.
The | character is for joining several conditions together in an OR statement. For example, if you wanted to find people with a last name of "smith", "jones", or "baker", you would use this filter:
(|(lastname=smith)(lastname=jones)(lastname=baker))
However, your filter only has one condition, so there's nothing for the | character to join together. Change your filter to this and it should work:
"(uid=" + username + "\*)"
By the way, what are you trying to do with the backslash and asterisk? Are you looking for people whose usernames actually end with an asterisk?
ok, this seems like it should be really simple but Im a bit confused:
i have two values - domain and ip
its best described with code:
whois_result = Popen(['whois', str(domain)], stdout=PIPE,stderr=STDOUT).communicate()[0]
debug_output(whois_result)
if 'Not found' or 'No entries' in whois_result:
print "Processing whois failure on '%s'" % str(domain)
print "Trying the IP (%s) instead..." % ip
whois_result = Popen(['whois', ip], stdout=PIPE,stderr=STDOUT).communicate()[0]
debug_output(whois_result)
if 'Not found' or 'No entries' in whois_result:
print "complete and utter whois failure, its you isnt it, not me."
return False
else:
test = re.search("country.+([A-Z].)",whois_result)
countryid = test.group(1)
so this function checks the domain whois, if it doesnt find it, its tries a whois with the ip address, but what I want to know is what is the best way to check if the domain is equal to None dont bother with the domain check and go onto the ip check, yet also if the domain is NOT equal to None, do the domain check and then the ip check in that order. Sorry if this is basic, this has me a bit confused. I guess i could set a variable and test for that but is there a more elegant way of doing it ?
if i put at the top a
if domain != None:
the only way it seems i can do it is by repeating the code or setting a variable, I guess there must be other conditional tests I could use that I dont know about.
EDIT: update 2 based on answers below: - ive also put in the country checking code with my database.
def do_whois(data):
if data is not None: return Popen(['whois', str(data)], stdout=PIPE,stderr=STDOUT).communicate()[0]
return 'No entries'
def check_whois(data):
conn = sqlite3.connect(db_name)
cursor = conn.cursor()
if 'No entries' in data or 'Not found' in data or 'No match for' in data:return False
id = re.search("country.+([A-Z].)",data)
if id is None:
print "we didnt get nuttin from whois"
return False
countryid = id.group(1)
# fetch country from countrycode db
cursor.execute("SELECT country,countrycode FROM countries WHERE countrycode = ?",(countryid,))
country = cursor.fetchone()
country = country[0]
print "Server is from: " + country
return (country,countryid)
def find_country(domain, ip):
return check_whois(do_whois(domain)) or check_whois(do_whois(ip))
part of the problem with making this robust is the varying values returned by the whois server eg for this IP: 67.222.137.216
the whois server returns :
# : whois 67.222.137.216
#
# Query terms are ambiguous. The query is assumed to be:
# "n 67.222.137.216"
#
# Use "?" to get help.
#
#
# The following results may also be obtained via:
# http://whois.arin.net/rest/nets;q=67.222.137.216?showDetails=true&showARIN=false&ext=netref2
#
BLUESQUAREDATAVPSLLC BLUESQUAREDATAVPSLLCNET (NET-67-222-137-213-1) 67.222.137.213 - 67.222.137.244
DFW Datacenter DFW-DATACENTER (NET-67-222-128-0-1) 67.222.128.0 - 67.222.159.255
#
# ARIN WHOIS data and services are subject to the Terms of Use
# available at: https://www.arin.net/whois_tou.html
#
thanks for any help.
Try this
def do_whois(data):
if data: return Popen(['whois', str(data)], stdout=PIPE,stderr=STDOUT).communicate()[0]
return 'No entries'
def check_whois(data):
if 'No entries' in data or 'Not found' in data:return False
test = re.search("country.+([A-Z].)",whois_result)
return test.group(1)
def find_whois(domain, ip):
return check_whois(do_whois(domain)) or check_whois(do_whois(ip))
This isn't going to work :
if 'Not found' or 'No entries' in whois_result:
This is interpreted as if ('Not found') or ('No entries' in whois_result) which always returns True.
To answer your question:
if domain != None && domain != 1:
-edit-
If you meant None instead of "one", you should simply put your IP checking code (which is to be executed after the domain check) on the same indenting level as the domain check.
This condition is wrong:
if 'Not found' or 'No entries' in whois_result:
It will always evaluate as "true", because the expression 'Not found' or 'No entries' in whois_result will always return 'Not found'.
You need to changed the if-statement to:
if 'Not found' in whois_result or 'No entries' in whois_result: