Only add to a dict if a condition is met

后端 未结 11 2078
鱼传尺愫
鱼传尺愫 2020-12-05 03:57

I am using urllib.urlencode to build web POST parameters, however there are a few values I only want to be added if a value other than None exists

11条回答
  •  囚心锁ツ
    2020-12-05 04:14

    Another valid answer is that you can create you own dict-like container that doesn't store None values.

    class MyDict:
        def __init__(self):
            self.container = {}
        def __getitem__(self, key):
            return self.container[key]
        def __setitem__(self, key, value):
            if value != None:
                self.container[key] = value
        def __repr__(self):
            return self.container.__repr__()
    
    a = MyDict()
    a['orange'] = 'orange';
    a['lemon'] = None
    
    print a
    

    yields:

    {'orange': 'orange'}
    

提交回复
热议问题