DanH
DanH

Reputation: 5818

Is there a more elegant way to add conditional dict elements

Take the following code for instance:

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)

Instead I was wondering if something similar to the following is possible:

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})

So instead needing to predefine args in order to add an optional element (limit) I could instead pass a variable which expands to a value:key. Somewhat similar to the way you can expand a dict to kwargs using `kwargs

Is this possible?

Upvotes: 1

Views: 464

Answers (2)

Thorsten Kranz
Thorsten Kranz

Reputation: 12765

You're searching for the .update()-method of Python's dict. You could do:

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)

Edit

The +-operator for dictionaries, as suggested in the comments, could be like:

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

Upvotes: 1

DanH
DanH

Reputation: 5818

Finally came up with the following thanks to 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))

Upvotes: 0

Related Questions