Friday Finking: Poly more thick

Christman, Roger Graydon dvl at psu.edu
Sat Feb 29 21:08:20 EST 2020


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.

Roger Christman
Pennsylvania State University


More information about the Python-list mailing list