以下面的代码为例:
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
这可能吗?
答案 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))