Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

Python: subset of key/value pairs of a dict determines the function to call

I dont know how to best describe my problem in one sentence in the title, so here the explanation:

I have a websocket connection and get data from it. The data is json format as string. There are for example 3 key/value pairs:

data = json.loads('{"k1":"id1_a","k2":"id2_a","k3":"value"}')

Now i want to call for different k1 and k2 combinations accordingly different functions.

My approach is the following: I defined a config file (yaml) like:

combination_a:
    k1: "id1_a"
    k2: "id2_a"
combination_b:
    k1: "id1_b"
    k2: "id2_b"
[...]

Then i can import the config file as dict and do the following:

import yaml
config = yaml.safe_load(open("config.yml"))

if config["combination_a"].items() <= data.items():
    function_a()
elif config["combination_b"].items() <= data.items():
    function_b()
[...]

Now two questions:

  1. How can i "map" the combination to a specific function, without using a big if elif [...] block? as far as i know, there is no switch function in python?
  2. Or is there a completely different, better solution?
question from:https://stackoverflow.com/questions/65836260/python-subset-of-key-value-pairs-of-a-dict-determines-the-function-to-call

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There isn't a switch function afaik, but you can define the combination->function mapping inside a dictionary and iterate over that to check which case applies.

If efficiency matters, you might even be able to find the relevant key inside the dict to have a faster lookuptime.

Here's the basic version:

combination_function_map = {
    'combination_a': function_a,
    'combination_b': function_b
}

for key, func in combination_function_map.items():
    if config[key].items() <= data.items():
        func()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...