[英]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.