Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
get.dictionary
#1
I am playing around with the idle again and am wondering how to best use the .get.

here is the code I'm messing around with.

people = {
    'howard' :'father',
    'maria' :'mother',
    'anthony' : 'child',
}

name = input('enter your name here: ')

while name != 0:
    print('')
    if name in people:
        print('hello ' + people.get(name) )
        break
    elif name not in people:
        print(name + 's not here man')
        break
#why does this print out 'hello father' and not hello howard?



I hope I tagged correctly this time.
Reply
#2
Your getting the value of howard. dicts are key: value pairs.
The while loop is not really needed if you're going to break after one go but, I left it in.

people = {
    'howard' :'father',
    'maria' :'mother',
    'anthony' : 'child',
}

while True:
    try:
        name = input('Enter name: ').lower()
        if name in people:
            print(f'Hello {name}.title()')
            break
        else:
            print(f'{name.title()}\'s not here.')
            break
    except ValueError as error:
        print(error)
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
When you iterate through a dictionary it returns keys. If all you want to do is get values you can use dict.values(). If you want to iterate through keys and values use dict.items()

I don't use dict.get() very much because I find it is easier to catch the key exception when a lookup fails instead of checking the return value. I will use dict.get(key, defaultValue) from time to time.
people = {
    'howard' :'father',
    'maria' :'mother',
    'anthony' : 'child',
}
 
try:
    name = input('Enter name: ')
    print(f'This is my {people[name.lower()]}, {name}.')
except KeyError as error:
    print('Who is', error)

name = input('Enter name: ').lower()
title = people.get(name.lower())
if title:
    print(f'This is my {title}, {name}.')
else:
    print(f'Who is {name}?')
Mostly a wash in this case. Nice to have choices.
Reply
#4
Thank you, im just messing around with what little I know so far, trying to build.
I enjoy learning python and appreciate everyone’s insights.
Also I would like to apologize for asking these child like questions.

Also thanks for the correction on while True try,
I would have kept on using while != .
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020