LoslegenKostenlos loslegen

Keyword arguments of variable size

Now let's move to keyword arguments of variable size! Your task is to define the function key_types(). It should take a variable number of keyword arguments and return a new dictionary: the keys are unique object types of arguments passed to the key_types() function and the associated values represent lists. Each list should contain argument names that follow the type defined as a key (e.g. calling the key_types(kwarg1='a', kwarg2='b', kwarg3=1) results in {<class 'int'>: ['kwarg3'], <class 'str'>: ['kwarg1', 'kwarg2']}).

To retrieve the type of an object, you need to use the type() function (e.g. type(1) is int).

Diese Übung ist Teil des Kurses

Practicing Coding Interview Questions in Python

Kurs anzeigen

Anleitung zur Übung

  • Define the function with an arbitrary number of keyword arguments.
  • Iterate over key-value pairs.
  • Update a list associated with a key.

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

# Define the function with an arbitrary number of arguments
def key_types(____):
    dict_type = dict()
    # Iterate over key value pairs
    for key, value in kwargs.____:
        # Update a list associated with a key
        if ____(____) in ____:
            dict_type[____].____
        else:
            dict_type[____] = [____]
            
    return dict_type
  
res = key_types(a=1, b=2, c=(1, 2), d=3.1, e=4.2)
print(res)
Code bearbeiten und ausführen