-1

I have a list ListA:

ListA = [ 'Key1: test1',  'Key2: test2', 'Key3: test3']

What I'm trying to do is I want to search a certain value to it respective key. For example: If user input test1, it should return me Key1 OR If user input test3, it should return me Key3 . I research a lot on the internet but it seem many are talking about comparing the two different list but not comparing the same list. I'm still new to programming, so I want to ask does my idea are lousy? Is it a better way to do it ?

WEI ZHUANG GOH
  • 303
  • 1
  • 7

1 Answers1

2

To solve the problem as originally presented:

from typing import Dict, List


ListA = ['Key1: test1',  'Key2: test2', 'Key3: test3']

def get_key_from_value_list(target_list: List, target_value: str):
    for entry in target_list:
        key, list_value = entry.split(":")
        if target_value == list_value.strip():
            return key

print("List:", get_key_from_value_list(ListA, "test1"))

Result:

List: Key1

But given that you mentioned you're deserialising JSON, you would be better off using the actual json module in Python to parse it so you get an actual dict object, which makes this much easier than dealing with a list. Doing so would then require:

from typing import Dict, List
import json

dict_a = json.loads('{"Key1": "test1","Key2": "test2","Key3": "test3"}')

def get_key_from_value_dict(target_dict: Dict, target_value: str):
    for key, value in target_dict.items():
        if target_value == value:
            return key

print("Dict: ", get_key_from_value_dict(dict_a, "test1"))

Result:

Dict:  Key1
Da Chucky
  • 694
  • 3
  • 13