是否有更优雅的方式来添加条件dict元素

时间:2013-01-17 07:26:53

标签: python dictionary kwargs

以下面的代码为例:

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的方式

这可能吗?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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))