1

I'm trying to create a dict in the following scenario

One list to save jobtype(s)

JOB_TYPE_LIST = ["PARTTIME", "FULLTIME", "WFH"] 

Corresponding list to each jobtype

PARTTIME_GROUP_LIST = ["PTGroup2", "PTGroup3"] FULLTIME_GROUP_LIST = ["FTgroup1", "FTgroup2"] WFH_GROUP_LIST = ["WFHgroup"] 

Expected dicts

dict { "PTGroup2": "PARTTIME", "PTGroup3": "PARTTIME", "FTgroup1": "FULLTIME", "FTgroup2": "FULLTIME", "WFHgroup": "WFH" } 

My current way to create this dict is do it manually. However, I would like to create this dict in a more pragramming way. Otherwise, every time I add a new jobtype and the corresponding list, I need to manually modify the dict.

Thanks in advance!

3 Answers 3

4

Maybe use dictionary instead of lists to store job types.

JOB_TYPES = { "PARTIME": ["PTGroup2", "PTGroup3"], "FULLTIME": ["FTgroup1", "FTgroup2"], "WFH": ["WFHgroup"] } expected_dict = {v: key for key, value in JOB_TYPES.items() for v in value} print(expected_dict) 

Output:

{'PTGroup2': 'PARTIME', 'PTGroup3': 'PARTIME', 'FTgroup1': 'FULLTIME', 'FTgroup2': 'FULLTIME', 'WFHgroup': 'WFH'} 
Sign up to request clarification or add additional context in comments.

Comments

2
output = {} JOBS_MAPPING = { "PARTTIME": PARTTIME_GROUP_LIST, "FULLTIME": FULLTIME_GROUP_LIST, "WFH": WFH_GROUP_LIST } for job_label, job_group_list in JOBS_MAPPING.items(): print(f"Job label is {job_label}, job groups list is {job_group_list}") for job_group in job_group_list: output.update({job_group: job_label}) print(ouput) > {'PTGroup2': 'PARTTIME', 'PTGroup3': 'PARTTIME', 'FTgroup1': 'FULLTIME', 'FTgroup2': 'FULLTIME', 'WFHgroup': 'WFH'} 

Comments

0

You may find this approach more flexible. Note that the json module is not required - it's just there to pretty-print the output.

Doing it this way means that you can change your list contents without having to change the code although the number of elements in the JOB_TYPE_LIST must match the number of other lists passed to the function.

import json JOB_TYPE_LIST = ["PARTTIME", "FULLTIME", "WFH"] PARTTIME_GROUP_LIST = ["PTGroup2", "PTGroup3"] FULLTIME_GROUP_LIST = ["FTgroup1", "FTgroup2"] WFH_GROUP_LIST = ["WFHgroup"] def func(job_type_list, *args): dict_ = {} for i, jt in enumerate(job_type_list): for group in args[i]: dict_[group] = jt return dict_ print(json.dumps(func(JOB_TYPE_LIST, PARTTIME_GROUP_LIST, FULLTIME_GROUP_LIST, WFH_GROUP_LIST), indent=2)) 

Output:

{ "PTGroup2": "PARTTIME", "PTGroup3": "PARTTIME", "FTgroup1": "FULLTIME", "FTgroup2": "FULLTIME", "WFHgroup": "WFH" } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.