import json
def word_exist_as_key(check):
with open('most_used_common.json',encoding="utf8") as file:
data = json.load(file)
if check in data:
return True
return False
z=word_exist_as_key(str("අංගනය"))
print(z)
In here the word "අංගනයක්"
exists but not "අංගනය"
. So I want to get "True"
for this value.
CodePudding user response:
import json
def word_exist_as_key(check):
with open('most_used_common.json',encoding="utf8") as file:
data = json.load(file)
return any(True for _ in data if check in _)
CodePudding user response:
You would essentially need to iterate through all the keys to see if any matched. Word of warning, depending on use case this could be less than a stellar idea as keys must all be unique.
import re
import json
def word_exist_as_key(check):
with open('most_used_common.json',encoding="utf8") as file:
data = json.load(file)
for key in data.keys():
if re.search(check, key) is not None:
return True
return False
z=word_exist_as_key(str("අංගනය"))
CodePudding user response:
I would personally suggest renaming the function to something like prefix_exists_in_dict
or maybe dict_has_key_prefix
, but in any case here's a simplistic approach you could take:
Loop over the keys in a dict, and if any key starts with a prefix, then immediately return True.
from typing import Any
def word_exist_as_key(data_dict: dict[str, Any], prefix: str):
for key in data_dict:
if key.startswith(prefix):
return True
return False
assert word_exist_as_key({'අංගනයක්': 'blah'}, 'අංගනය')
As mentioned in comments, if you are not interested in checking if a key starts with a value, rather you want to see if a key contains a value at all, then it becomes much simpler. In the above code, you would simply remove str.startswith
usage and just replace it with an in
check:
if prefix in key: