I have a dictionary called to_nato that looks like this:
to_nato = {'a': 'alfa',
'b': 'bravo',
'c': 'charlie',
'd': 'delta',
'e': 'echo',
'f': 'foxtrot',
'g': 'golf',
'h': 'hotel',
'i': 'india'}
I need to write loop to iterate over a string "stateofny" and for each letter, if it is in a dictionary, append that word to the end of syr_list
I am trying this:
syr_str="stateofny"
syr_list=[]
for letter in syr_str:
for key, value in zip(to_nato.keys(), to_nato.values()):
if letter == key:
syr_list.append(value)
print(syr_list)
but it returns empty list. What am I doing wrong?
>Solution :
Your method works fine, it doesn’t return an empty list (assuming that you had a typo in your post, and your to_nato is actually a valid dictionary). That being said, that’s not how you use a dictionary. The sole purpose of a dictionary is to make it easier to randomly access elements, without using for loops and if statements.
This is a better version of your code:
for letter in syr_str:
if letter in to_nato:
syr_list.append(to_nato[letter])
Or, using a list comprehension:
syr_list = [to_nato[letter] for letter in syr_str if letter in to_nato]