简体   繁体   English

基于另一本字典的 bool 创建字典列表的最 Pythonic 方法

[英]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.然后我在其他地方定义了另外三个dict ,我们可以想象我们导入了它们,因此它们作为变量存在于模块的命名空间中。

 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.现在,我想根据上面 dict 的 bool 创建一个包含那些dict的列表。

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.我只是想知道是否有更 Pythonic 的方式 - 这是非常可读但不是很 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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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