Reputation: 19
I have done a large amount of searching but cannot find what I am after. I am using Iron Python.
I have a large list of strings (MyList) that I have extracted and I would like to see if there are values that contain the Items in the SearchStrings Dictionary. The searchStrings Dictionary could have over 500 items within.
MyList = ["123steel","MylistConcrete","Nothinginhere","45","56","steel","CONCRETE"]
SearchStrings = {'concrete' : 'C','CONCRETE' : 'C','Steel' : 'S', 'STEEL' : 'S'}
I need to return the index and then matching code from the SearchString.
i.e If we find 'MylistConcrete'
i will know the index '1' and can return 'C'
I hope this makes sense to everyone. Let me know if you need any clarification
Thanks in Advance,
Geoff.
Upvotes: 0
Views: 75
Reputation: 3138
First of all, I'd suggest you to use string.lower()
to eliminate case dependencies in the search. This will make your dictionary smaller and more manageable.
Then you can use a simple map function to create a new array with your values while preserving the index (or alter the original should you require that).
MyList = ["123steel","MylistConcrete","Nothinginhere","45","56","steel","CONCRETE"]
SearchStrings = {'concrete' : 'C', 'steel' : 'S'}
def check_search_strings(x):
for k, v in SearchStrings.items():
if k in x.lower():
return v
return None
indexes = list(map(check_search_strings, MyList))
print (indexes)
Upvotes: 2
Reputation: 23556
for m in MyList :
for k in SearchStrings :
if k.lower() in m.lower() :
print 'found', k, 'in', m, 'result', SearchStrings[k]
Upvotes: 1
Reputation: 6223
Iterate over your items in MyList
and check for every item (lowercase) if any of the dict's (lowercase) keys is in it. Then replace.
This assumes that you don't have different values for identical words as keys (except for lower- / uppercase difference)
my_list = ["123steel", "MylistConcrete", "Nothinginhere", "45", "56", "steel", "CONCRETE"]
search_strings = {'concrete': 'C', 'CONCRETE': 'C', 'Steel': 'S', 'STEEL': 'S'}
for i in range(len(my_list)):
for k, v in search_strings.items():
if k.lower() in my_list[i].lower():
my_list[i] = v
break # avoids completing the loop if first item is found
print(my_list)
The result is
['S', 'C', 'Nothinginhere', '45', '56', 'S', 'C']
Upvotes: 1