I know this is a newbie question. But I'm still having trouble using .strip() and .title() with a list or a dictionary. I'd like to normalize both but can't find how.
favorite_languages = { 'JENNA': 'python', 'louis': 'C', 'liOnEl': 'Ruby', 'maude': 'Javascript', } friends = [' JeNNa', 'LIONEL '] for name in favorite_languages.keys(): print(name.title().strip()) if name.title().strip() in friends: print("Hi " + name + ", I can see your favorite language is " + favorite_languages[name] + "!") 21 Answer
First, normalise your favorite_languages:
In [605]: fav_lang_norm = { x.strip().title() : favorite_languages[x] for x in favorite_languages }; fav_lang_norm Out[605]: {'Jenna': 'python', 'Lionel': 'Ruby', 'Louis': 'C', 'Maude': 'Javascript'} Then, normalise your friends list:
In [606]: friends_norm = [x.strip().title() for x in friends]; friends_norm Out[606]: ['Jenna', 'Lionel'] Iterate over the normalised dictionary:
for name, language in fav_lang_norm.items(): if name in friends_norm: print("Hi " + name + ", I can see your favorite language is " + language + "!") You'd better hope your friends list is case insensitive...
Second approach, consider you have a huge favorite_languages dictionary with a million records:
favorite_languages = {...} # 1 million Step 1: Normalise your favourite_languages dict only:
fav_lang_norm = { x.strip().title() : favorite_languages[x] for x in favorite_languages } Step 2: Iterate over your friends list:
for name in friends: # friends is not normalised name_norm = name.strip().title() if name_norm in fav_lang_norm: print("Hi " + name_norm + ", I can see your favorite language is " + fav_lang_norm[name_norm] + "!") 13