1

以下面的代码为例:

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我可以改为传递一个扩展为 value:key 的变量。有点类似于使用 ` kwargs将 dict 扩展为 kwargs 的方式

这可能吗?

4

2 回答 2

1

您正在寻找.update()Python 的 dict 的 -method。你可以这样做:

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)

编辑

正如评论中所建议的,字典的+-operator 可能类似于:

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
于 2013-01-17T07:30:52.833 回答
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))
于 2013-01-17T07:40:15.970 回答