[英]Is there a more elegant way to add conditional dict elements
以以下代码为例:
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将字典扩展为kwargs的方式
这可能吗?
您正在搜索Python字典的.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
最后感谢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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.