Home > Net >  How to check the dict results if the input is only part of the keyword?
How to check the dict results if the input is only part of the keyword?

Time:04-13

I have a dict and input like that, and now I want to it can search the input even though it is only part of key words, so how to solve it?

input = "a"
dict = {'aaa':111,'bbb':222,'ccc':333}
print(dict[input])

P.S Assuming there is no conflict between input and dict keywords, for example,

input ='a'
dict = {'aaa':111,'abc':222}

is impossible

CodePudding user response:

If there can be no conflict, or if you're happy to take the first key that matches the input if there is, you could search the keys to find one which starts with the input string:

input = "a"
dic = {'aaa':111,'bbb':222,'ccc':333}
dic[[k for k in dic.keys() if k.startswith(input)][0]]

Output:

111

CodePudding user response:

Try this. (Python 3.x)

input = "a"
dict = {'aaa':111,'bbb':222,'ccc':333}

def find(inp, dct):
    for k in dct.keys():
        if inp.lower() in k.lower():
            return dct[k]
    return "NOT FOUND"

print(find(input, dict))

CodePudding user response:

One way (although not the simplest one) would be subclassing dict.

code00.py:

#!/usr/bin/env python

import sys


class LooseKeyDict(dict):
    def __matching_keys(self, key):
        return [e for e in self.keys() if key in e]

    def __getitem__(self, key):
        mc = self.__matching_keys(key)
        if not mc or len(mc) > 1:
            raise KeyError(key)
        return super().__getitem__(mc[0])


def main(*argv):
    d0 = LooseKeyDict({"aaa": 111, "bbb": 222, "ccc": 333})
    print(d0["a"])
    print(d0["aaa"])
    try:
        print(d0["aaa1"])
    except KeyError as ke:
        print("KeyError:", ke)

    d1 = LooseKeyDict({"aaa": 111, "abc": 222})
    try:
        print(d1["a"])
    except KeyError as ke:
        print("KeyError:", ke)


if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.")
    sys.exit(rc)

Output:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q071851970]> "e:\Work\Dev\VEnvs\py_pc064_03.09_test0\Scripts\python.exe" code00.py
Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] 064bit on win32

222
222
KeyError: 'aaa1'
KeyError: 'a'

Done.

Notes:

  • This is only for the read part. If you want to also do it for write (or delete), you'd have to also override __setitem__ (or __delitem__). More details on [Python.Docs]: Data model
  • Don't name your variables input or dict, as you're shadowing built-in names
  • Related