I am currently going through the book “Python Crash course” by Eric Matthes, and I am having a really hard time understanding some of the code. I am teaching myself just because I think coding could be a really fun hobby. So here is what I am struggling with.
Chapter 6 Dictionaries and If you own the book it is favorite_languages.py on pg 102.
favorite_languages = {
‘jen’ : ‘python’,
'sarah : ‘c’,
‘edward’ : ‘ruby’,
‘phil’ : ‘python’,
}
friends = [‘phil’, ‘sarah’]
for name in favorite_languages.keys():
print(f"Hi {name.title()}.")
if name in friends:
language = favorite_languages[name].title()
print(f"\t{name.title()}, I see you love {language}!")
We get the output
Hi Jen.
Hi Sarah.
Sarah, I see you love C!
Hi Edward.
Hi Phil.
Phil, I see you love Python!
I understand what they are trying to do, but my brain does not understand the coorelations, and why we are getting that output. So i was hoping someone could break this down for me and explain exactly whats going on.
Hey @Lundo1 and welcome to the GitHub Community Forum! Yes, coding could definitely be a fun hobby and everyone can learn! Let me break down the code step-by-step for you.
# Below here, a dictionary is defined. Just like in real life, a
# dictionary in Python maps so-called "keys" (in real-life the words,
# but in this case some names) to "values" (in real-life the
# definitions, but in this case their favorite programming language).
favorite_languages = {
'jen' : 'python',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'python’'
}
# Here, we create a list that contains names of your friends:
friends = ['phil', 'sarah']
# Here we make a for-loop. We loop through the keys, since the keys()
# method of a dictionary returns a list of the keys. In this case:
# favorite_languages.keys() = ['jen', 'sarah', 'edward', 'phil'].
# Similarly, you could also use .values() for the items, or .items()
# for both the key and the value, like:
# > for name, fav_language in favorite_languages.items():
# > ...
for name in favorite_languages.keys():
# Using an f-string we print the name. See what is going
# on in an f-string?
print(f'Hi {name.title()}.')
if name in friends: # If the current name is in the friends list
# Determine their favorite language. Using square
# brackets ( [ and ] ) you can access values from a
# dictionary. In your case: favorite_languages['phil'] == 'python'.
# The .title() may be a bit confusing, but that method just capitalizes
# the first letter of the programming language. Leave it out and test
# what happens!
language = favorite_languages[name].title()
# Again, print some info using an f-string.
print(f'\t{name.title()}, I see you love {language}!')
Hope it helps! If you have any further questions, let us know!