如何以更加pythonic的方式编写函数?

时间:2014-07-25 17:00:07

标签: python

我得到了用python编写的以下函数。

def get_campaign_id(campaigns, campaign_name):
  for c in campaigns:
    if c['name'] == campaign_name:
      return c['id']
  return None

广告系列是一系列文字,例如:

campaigns = [{'name': 'campaign1', 'id': 91203}]

和campaign_name是str

1 个答案:

答案 0 :(得分:1)

mapping =dict([c["name"],c["id"]) for c in campaigns]) #save this ... dont recreate it all the time
print mapping[campaign_name] # get the id by campaign name

可能是更好的方法......