2013-01-17 30 views
0

就拿下面的代码:有没有更优雅的方式来添加条件字典元素

def facebook_sync_album(album_id, thumbnails_only=False): 
    args = {'fields':'id,images,source'} 
    if thumbnails_only: 
     args['limit'] = ALBUM_THUMBNAIL_LIMIT 
    response = facebook_graph_query(album_id, 'photos', args=args) 

相反,我在想,如果类似下面的东西是可能的:

def facebook_sync_album(album_id, thumbnails_only=False): 
    photo_limit_arg = {'limit': ALBUM_THUMBNAIL_LIMIT} if thumbnails_only else None 
    response = facebook_graph_query_by_user_profile(album_id, 'photos', args={'fields':'id,images,source', photo_limit_arg}) 

所以不是需要预先定义args以便添加一个可选元素(limit)我可以改为传递一个变量,将其展开为值:key。有点类似于你可以使用'kwargs

扩展字典给kwargs这可能吗?

+0

是你的'ar gs = {'fields':'id,images,source',photo_limit_arg}'在第一个代码块中真的是'args = {'fields':'id,images,source'}'? ',photo_limit_arg'部分在这里没有意义。 – glglgl

+0

是的好点,我会解决,谢谢! D: – DanH

回答

1

您正在搜索.update()-Python的字典方法。你可以这样做:

def facebook_sync_album(album_id, thumbnails_only=False): 
    args = {'fields':'id,images,source'} 
    args.update({'limit': ALBUM_THUMBNAIL_LIMIT} if thumbnails_only else {}) 
    response = facebook_graph_query_by_user_profile(album_id, 'photos', args=args) 

编辑

+ - 运算符的字典,如评论所说,可能是这样的:

class MyDict(dict): 
    def __add__(self, other): 
     if not isinstance(other, dict): 
      return super(MyDict, self).__add__(other) 
     return MyDict(self, **other) 

    def __iadd__(self, other): 
     if not isinstance(other, dict): 
      return super(MyDict, self).__iadd__(other) 
     self.update(other) 
     return self 

if __name__ == "__main__": 
    print MyDict({"a":5, "b":3}) + MyDict({"c":5, "d":3}) 
    print MyDict({"a":5, "b":3}) + MyDict({"a":3}) 

    md = MyDict({"a":5, "b":3}) 
    md += MyDict({"a":7, "c":6}) 
    print md 
+0

这并不比原来更干净。如果内建的工作方式类似于+列表(它会复制一个,然后调用update并返回结果),那么会很好,但是可惜的是没有一个。 – Dougal

+0

我喜欢这个,但最终我用'dict(dict1,** dict2)'来到那里。谢谢! – DanH

+1

对于'+':你可以创建自己的字典类,继承'dict'。确实很有趣(请参阅我的编辑)。 –

0

最后用下面的感谢想出了https://stackoverflow.com/a/1552420/698289

def facebook_sync_album(album_id, thumbnails_only=False): 
    photo_limit_arg = {'limit': ALBUM_THUMBNAIL_LIMIT} if thumbnails_only else {} 
    response = facebook_graph_query_by_user_profile(album_id, 'photos', args=dict({'fields':'id,images,source'}, **photo_limit_arg)) 
相关问题