Friday Finking: Poly more thick

MRAB python at mrabarnett.plus.com
Sat Feb 29 21:33:26 EST 2020


On 2020-03-01 02:08, Christman, Roger Graydon wrote:
> DL Neil asked:
> 
>> How does one code a function/method signature so that
>> it will accept either a set of key-value pairs,
>> or the same data enclosed as a dict, as part of
>> a general-case and polymorphic solution?
> 
> 
> Will this do for you?
> 
> def any_as_dict(*args, **kwargs):
> if len(args) == 0:
> my_dict = kwargs
> elif type(args[0]) == type(dict()):
> my_dict = args[0]
> else:
> my_dict = dict(args)
> print(type(my_dict),my_dict)
> 
> 
>>>> any_as_dict(a=1,b=2)
> <class 'dict'> {'a': 1, 'b': 2}
>>>> any_as_dict({'a':1, 'b':2})
> <class 'dict'> {'a': 1, 'b': 2}
>>>> any_as_dict([('a',1), ('b',2)])
> <class 'dict'> {('a', 1): ('b', 2)}
>>>> any_as_dict({('a',1), ('b',2)})
> <class 'dict'> {('b', 2): ('a', 1)}
> 
> This seems to address your apparent definition of
> "key-value pairs" in the form of a=1, b=2
> and my interpretation as key-value tuples,
> either in a list, or set, or presumably any
> iterable collection, in addition to taking an
> actual dictionary.
> 
That function can be simplified:

def any_as_dict(*args, **kwargs):
     return dict(args[0]) if args else kwargs

>>> any_as_dict(a=1,b=2)
{'a': 1, 'b': 2}
>>> any_as_dict({'a':1, 'b':2})
{'a': 1, 'b': 2}
>>> any_as_dict([('a',1), ('b',2)])
{'a': 1, 'b': 2}
>>> any_as_dict({('a',1), ('b',2)})
{'b': 2, 'a': 1}


More information about the Python-list mailing list