Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to iterate over a string and for each letter, if it is in a dictionary, append that word to the end of `syr_list`

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading