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 に答える