sruthi kadukuntla February 2016

I want to convert a string into list

I am giving a string like d='direct'
expected o/p= match found for direct
but i am getting like match not found for d
match not found for i, match not found for r etc. for now i am using a code:

dict1={'d': 'direct', 't': '2',  'g': ['D','D']}
dict2={'d': 'direct', 'u': ['2', '2'], 't': ['2', '2'],  'g': ['D', 'D']}

for key in dict1:
    for index, element in enumerate(dict1[key]):
        if element in dict2[key]:
            print("Match found for", element)
        else:
            print("Match not found for", element)

Answers


hpaulj February 2016

dict1[key] returns 'direct'. Try:

for i in 'direct':
   print(i)

You'll find that it prints: d i r ....

That's what your code is doing:

match not found for d
match not found for i
match not found for r etc

Iterating over a string gives you the individual characters.

Changing dict1 to

dict1={'d': ['direct'], ...}

will at least get you past the 1st key. Assuming, that is, you want to test for 'direct' in the second dictionary. Make the same change in dict2. In other words, be careful about mixing up strings and lists. Sometimes a string behaves like a list.

Look also at list('direct'), or for i in list('direct'):.... That's probably not the string to list conversion that you want - but sometimes it's useful.


Karthikeyan February 2016

Try this code,

dict1={'d': 'direct', 't': '2',  'g': ['D','D']}
dict2={'d': 'direct', 'u': ['2', '2'], 't': ['2', '2'],  'g': ['D', 'D']}

for key1 in dict1:
   for key2 in dict2:
        if key1 in key2:
            print dict1[key1]

You are iterating over the dict1, which compares the individual chars.


Mustafa February 2016

Is this below op what you want?

dict1={'d': 'direct', 't': '2',  'g': ['D','D']}
dict2={'d': 'direct', 'u': ['2', '2'], 't': ['2', '2'],  'g': ['D', 'D']}

#for key in dict1:
    #print key

for key in dict1:
    for index, element in enumerate(dict1[key]):
        #print key, index, element
        if element in dict2:
            print("Element {0} found".format(element))
        else:
            print("Element {0} not found".format(element))

Element d found Element i not found Element r not found Element e not found Element c not found Element t found Element D not found Element D not found Element 2 not found

Post Status

Asked in February 2016
Viewed 2,697 times
Voted 6
Answered 3 times

Search




Leave an answer