开发者

Dynamic field insertion when creating python dictionary

开发者 https://www.devze.com 2023-04-02 21:10 出处:网络
I would like to dynamicly add/ don\'t add a field when creating a python dictionary. def my_func(input):

I would like to dynamicly add/ don't add a field when creating a python dictionary.

def my_func(input):
    return {
         'foo':'bar',
         None if input == None else 'baz':input
        }

This actually works but it returns {'foo': 'bar', None: None}

I would like it to re开发者_C百科turn {'foo': 'bar'}. Is there a way to do that?

PS. I know this question is a bit academic. One could easily do:

def my_func(input):
    ret = {
         'foo':'bar',
            }
    if input != None:
        ret['baz'] = input
    return ret

but I like the first one for cleanness.

[EDIT]

Could we use an __metaclass__ to solve this?


You be wanting collections.defaultdict

collections.default works like a normal dict with one exception, you can set a default_factory, when you do a['test'] and the key is __missing__ then it will call default factory. In default factory you can make it do anything you want to give it a default value.


I totally agree with jellybean. but if you really need it, and really need it as oneliner, then you can do something like:

def my_func(input):
   return dict([(k,v) for k,v in (('foo', 'bar'), ('buz', inp)) if v])

Of course it doesn't cover case when some other values are also None... (And it's ugly. I really don't know why i've posted this :) )

And, imho, second variant you posted is absolutely ok in your case.

def my_func(input):
    ret = {'foo':'bar'}
    if input:
        ret['baz'] = input
    return ret
0

精彩评论

暂无评论...
验证码 换一张
取 消