Python Forum
Find a substring in a dictonary; value substring of key
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Find a substring in a dictonary; value substring of key
#1
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)
Reply
#2
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.
Reply
#3
You need an if statement with the in operator:

>>> 'Rob' in 'Sir Robin'
True
>>> 'Bravery' in 'Sir Robin'
False
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Finding how many times substring is in a string using re module ranbarr 4 2,943 May-21-2021, 06:14 PM
Last Post: nilamo
  Substring in a string Propoganda 1 2,219 Dec-01-2019, 08:45 AM
Last Post: perfringo
  Dictonary and list help Btoulouse 3 2,872 Dec-10-2018, 10:52 AM
Last Post: Larz60+
  Python: Returning the most frequently occurring substring in a larger string sskkddrit 2 3,865 Feb-09-2018, 06:41 AM
Last Post: sskkddrit
  [Discussion] Re. Substring counting Mekire 9 5,226 Jan-22-2018, 01:56 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020