Python Forum

Full Version: Find a substring in a dictonary; value substring of key
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Question: Find a substring

You are given a dictionary of the US states and their capitals (my actual list is larger than provided below). The keys in the dictionary are states and the values are capital names.

Write a code to return a list of all capitals that contain the name of a state in their name as a substring.

HINT: For example, Indianapolis as a capital name and Indiana as a state name is one of the key/value pairs that your code would find. Your code should add Indianapolis to the list. After you found all capitals and added them to the list, print out the list.

Run this cell to create a dictionary of states' capitals
capitals={ 'Illinios': 'Springfield', 'Indiana': 'Indianapolis', 'Oklahoma': 'Oklahoma City', 'Oregon': 'Salem', }
I believe I have to use substring or contains. I am new to Python. I appreciate it, thank you.

capitals={capital:state} 
list_of_all_capitals=[] 
for capital in state 
list_of_all_capitals.append=[capital] 
print(list_of_all_capitals)
You can use in to check if something is in something else
print('something' in 'something else')
Output:
True
You need to look up for loops and how to indent them, how to iterate over dictionary's key/values, and using if statements.
You need an if statement with the in operator:

>>> 'Rob' in 'Sir Robin'
True
>>> 'Bravery' in 'Sir Robin'
False