简体   繁体   中英

most pythonic way to create list of dictionaries based on bool of another dictionary

Here's my situation - I have a dictionary:

dic = {"al" : False,
       "ol" : True,
       "psc": True,
       "cp" : False}

Then I have three other dict s defined somewhere else which we'll just imagine we imported, so they exist as variables in the namespace of the module.

 appointmentslist_params  # al 
 officerlist_params       # ol
 psc_params               # psc
 companyprofile_params    # cp

Now, I want to create a list containing those dict s based on the bool of the dict above.

My current solution is:

params_ls = []
if dic["ol"]:
    params_ls.append(officerlist_params)
if dic["psc"]:
    params_ls.append(psc_params)
if dic["al"]:
    params_ls.append(appointmentslist_params)
if dic["cp"]:
    params_ls.append(companyprofile_params)

I was simply wondering if there was a more pythonic way - this is very readable but not very DRY.

You could use another dictionary to associate the imported dictionaries with the corresponding key:

d1 = {'al':appointmentslist_params, 'ol':officerlist_params, 'psc':psc_params, 'cp':companyprofile_params}
dic = {"al" : False,
   "ol" : True,
   "psc": True,
   "cp" : False}

params_ls = [b for a, b in d1.items() if dic[a]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM