首页 > 解决方案 > How to search a partial text in dict?

问题描述

I have a dictionary and would like to be able to search with a partial variable and return a text.

df = pd.read_csv('MY_PATH')
d = defaultdict(lambda: 'Error, input not listed')
d.update(df.set_index('msg')['reply'].to_dict())
d[last_msg()]

last_msg() should be my partial variable, and d is my dictionary.

The index on my dictionary is column msg from df.

In column msg i have a sample like Jeff Bezos.

In column reply i have a matching reply Jeff Bezos is the CEO of Amazon

How can I search a partial value in column msg and return matching value from column reply?

I want to search just Jeff or just Bezos and get the matching reply Jeff Bezos is the CEO of Amazon

PS. Alternatives to defaultdict may also help improve the code.

EDIT: last_msg() code extracts a text from selenium element.

def last_msg():
try:
    post = driver.find_elements_by_class_name("_12pGw")
    ultimo = len(post) - 1
    texto = post[ultimo].find_element_by_css_selector(
        "span.selectable-text").text
    return texto
except Exception as e:
    print("Error, input not valid")

When I print(d):

defaultdict(<function <lambda> at 0x0000021F959D37B8>, {'Jeff Bezos': 'Jeff Bezos is the CEO of Amazon', 'Serguey Brin': 'Serguey Brin co-founded Google', nan: nan})

When I print(df)

   Unnamed: 0           msg                            reply
0           0    Jeff Bezos  Jeff Bezos is the CEO of Amazon
1           1  Serguey Brin   Serguey Brin co-founded Google
2           2           NaN                              NaN
3           3           NaN                              NaN

标签: pythonpandasseleniumdictionary

解决方案


我找到了一种方法来解决我自己的问题:

d = df.set_index('msg')['reply'].to_dict()
...
        try:
        x = next(v for k, v in d.items() if last_msg() in k)
    except StopIteration:
        x = 'Error, input not listed'

推荐阅读