0

I created a dictonary with Key and Value and want to write a Loop in a Loop:

for key,val in dict.items():
 def contains(x, y):
    result = np.nan
    for i in x:
        if i.lower() in y.lower():
            result = key
    return result
    df['Test'] = df['Countrylist'].apply(lambda x: contains([val], x))

So I want to check if the Value in the Dictonary is in the Countrylist and if yes, then give the new Column Test the Value of the Key in the Dictonary.

But my code doesnt work...

Expected Output:

Countrylist  Bla1 Bla2   Test
Germany       12  12    "Here should be the Key of the Dic"

1 Answers1

1

Per comment:

def contains(x, y):
    for i in x:
        if i.lower() in y.lower():
            return True
    return False

for key,val in dict.items():
    df['Test'] = df['Countrylist'].apply(lambda x: key if contains([val], x) else np.nan)

Again, since you provide no input/output pair, it's hard to check if that does what you want. In particular, contains(['foo', 'bar'], 'FOOTBALL') == True (which might be what you want but is not obvious from the name of the function).

Furthermore, notice that this code is reassigning df['Test'] multiple times in the loop. The final value of that column depends on which loop iteration is the last one (which is not something you can rely on for Python versions <= 3.5-3.6, see the accepted answer here).

Leporello
  • 468
  • 2
  • 12