2

is there a better way of checking if multiple key exists in a dictionary and assigning multiple values to a variable based on the key found in the dictionary. instead of multiple ifs??

name = None
type_of_transaction = None
customer = None
transaction_id = None
for key, value in data_value.items():
  if "unique_element" in key:
      customer = value
  if "type" in key:
      type_of_transaction = value
  if "product_name" in key:
      name = value
  if "transactionId" in key:
      transaction_id = value
Brian61354270
  • 8,690
  • 4
  • 21
  • 43
ray1251
  • 21
  • 2
  • 2
    Does this answer your question? [Why dict.get(key) instead of dict\[key\]?](https://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey) – Brian61354270 Apr 05 '21 at 03:50
  • If ```data_value = {"type unique_element": 123}``` or similar the if statements work, but not in a way that seems likely. The right answer will change depending on the missing context. – jwal Apr 05 '21 at 04:30

1 Answers1

0

If the key strings are exact matches it is as easy as:

customer = data_value.get("unique_element")

If the key is not found get will return None

If you are looking for partial key names I suggest looking at the nested-lookup library

You can used the nested_lookup function with wildcards to find all the keys containing the string "unique_element" and their values:

results = nested_lookup(
    key = "mail",
    document = my_document,
    wild = True,
    with_keys = True,
)

print(results)

output:

{
 "email_address": ["test1@example.com", "test4@example.com"],
 "secondary_email": ["test2@example.com"],
 "EMAIL_RECOVERY": ["test3@example.com"]
}
NirO
  • 216
  • 2
  • 12