Reputation: 2436
I have a dictionary and I want to see if astring contains any of the keys in the dictionary. If so, I want to replace it with the corresponding value in the dictionary.
states = {
'Alaska' : 'AK',
'Alabama' : 'AL',}
astring = "I love Alaska"
for state in states:
if state in astring:
print astring.replace(state, state.value())
This doesn't work of course because in iterating through the keys with the For loop, python is treating state as a string. As a result, there is no value() for state.
Upvotes: 1
Views: 84
Reputation: 3410
Another way, slower but shorter:
import re
states = {
'Alaska' : 'AK',
'Alabama' : 'AL',
}
# build a regexp
pattern = re.compile(
r'\b(%s)\b' % '|'.join(re.escape(needle) for needle in states)
)
astring = "I love Alaska"
print pattern.sub(lambda match: states.get(match.group()) or match.group(), astring)
Upvotes: 0
Reputation: 5362
Consider the case where astring= 'I love Alaska and Alabama'
. then use
new_string = ' '.join([states[word] if word in states else word for word in astring.split()])
#'I love AK and AL'
Upvotes: 0
Reputation: 9986
You can just use the key from the for
loop as the key to your states dict. This should work for you.
states = {
'Alaska' : 'AK',
'Alabama' : 'AL',}
astring = "I love Alaska"
for state in states:
if state in astring:
print astring.replace(state, states[state])
It's probably less efficient, but you could also do this
states = {
'Alaska' : 'AK',
'Alabama' : 'AL',}
astring = "I love Alaska"
for state, abbreviation in states.items():
if state in astring:
print astring.replace(state, abbreviation)
Upvotes: 3
Reputation: 12213
Your variable state
is a string, and has no method .value()
. I recommend iterating through the entries when you want to use both the key and the value:
for state, abbr in states.items():
if state in astring:
print astring.replace(state, abbr)
Upvotes: 3