NBA
NBA

Reputation: 37

Comparing and replacing elements of a list

I have a dictionary :-

   dict= { 'b' : 'bob' , 'c' : 'code' , 'd' : 'do'}
import re
def convert(str)
 data=list(str.replace(' ',''))
 for dat in data
 print dat
 # this gives an output as
 # b
 # c
 # d
 # Here I want to compare each character(b,c,d) with the key in my dict{} dictionary
 # and if there is a match(dict has 'b':'bob') then I want to replace the character with the 
 # dictionary value.
 # In summary i want to convert string bcd to bobcodedo.


if __name__== "__main__":
 sam('bcd')

In summary i want to convert string bcd to bobcodedo.

Upvotes: 1

Views: 63

Answers (1)

CT Zhu
CT Zhu

Reputation: 54330

Don't name your dictionary dict, string str, etc.

In [12]:

D={ 'b' : 'bob' , 'c' : 'code' , 'd' : 'do'}
S='bcd'
In [13]:

''.join(map(D.get,S))
Out[13]:
'bobcodedo'

To expand it to your second question:

In [15]:

''.join(map(lambda x: D.get(x, ''),'bcdefg'))
Out[15]:
'bobcodedo'
In [16]:

''.join(map(lambda x: D.get(x, x),'bcdefg'))
Out[16]:
'bobcodedoefg'

To answer the question in your comment:

In [12]:

bad_str='|xyz'
in_str1='acdefggt'
in_str2='asxsttgm'
In [13]:

set(bad_str).intersection(in_str2)
Out[13]:
{'x'}
In [14]:

if len(set(bad_str).intersection(in_str1))==0:
    print 'do someting'
else:
    print 'Abort!'
do someting

Upvotes: 3

Related Questions