3

I am trying to create my first function using kwargs and I'm having some trouble with the looping.

I am passing two kwargs: tick and start. Both tick and start are going to be strings or lists of strings.

I want to loop through the kwargs to categorize them using if elif and contain with the proper string and the kwarg

when the kwarg passes the test I want to take that kwarg's values and append it/them to the list matching its name list (ie. tick goes into tick list)

At the moment I am taking all the kwargs values and appending them to the list not the kwarg's value that I am working on.

There is a distinction between kwarg, kwargs and kwarg's sorry it that is confusing.

def fn1(**kwargs):
    ticks = []
    start = []

    # Iterating over the Python kwargs dictionary

for kwarg in kwargs: # For each kwarg in kwargs
        if "ticks" in kwarg:   #Test if "tick" in kwarg. If yes continue to line below, if not skip the next two lines
            for kwarg in kwargs.values():  #for each i in kwargs values  THIS IS WRONG
                    ticks.append(kwarg)
                    break  # I use this to fix what is wrong 

        elif "start" in kwarg:
                for kwarg in kwargs.values(): #Same problem as 5 lines up, and now I do not know how to either skip the first iteration of the loop or fix the original problem
                    start.append(kwarg)

    print(ticks, start)

Input:

fn1(ticks= ["IBM", "AAPL"], start= "2")

Output:

[['IBM', 'AAPL']] [['IBM', 'AAPL'], '2']

Desired Output:

[['IBM', 'AAPL']] ['2']
Josh_VC
  • 66
  • 4
  • Does this answer your question? [What is the purpose and use of \*\*kwargs?](https://stackoverflow.com/questions/1769403/what-is-the-purpose-and-use-of-kwargs) – tevemadar Dec 13 '19 at 00:00

2 Answers2

1

You have one too many for loops. When you use **kwargs it creates a dictionary called kwargs.

fn1(ticks= ["IBM", "AAPL"], start= "2")

will create a dictionary like this:

{'ticks': ['IBM', 'AAPL'],
 'start': '2'}

You're looping through the keys, and then all the values for every matching key.

If you get rid of the outer for loop, you can just check if the given string is in the dictionary. Then you can loop over the values of that key.

def fn1(**kwargs):
    ticks = []
    start = []

    if "ticks" in kwargs:
        for kwarg in kwargs['ticks']:
            ticks.append(kwarg)
    elif "start" in kwargs:
        for kwarg in kwargs['start']: 
            start.append(kwarg)
    print('Ticks: {}'.format(ticks))
    print('Start: {}'.format(start))

But given you're just appending everything to a dictionary, you might just do away with the loops all together, and just use the values straight from the dictionary.

def fn1(**kwargs):
    print('Ticks: {}'.format(kwargs.get('ticks', [])))
    print('Start: {}'.format(kwargs.get('start', [])))

Bear in mind that in your provided example result, the start is a list, but you're providing a string. If you want start to be a list you should provide start=['2'].

Dan D.
  • 73,243
  • 15
  • 104
  • 123
blueteeth
  • 3,330
  • 1
  • 13
  • 23
1

Not sure about logic in your source code, but I did a working solution that returns the desired output.

def fn1(**kwargs):
    ticks = []
    start = []

    for kwarg, values in kwargs.items():  # For every kwarg in kwargs
        if kwarg == "ticks":
            ticks.append(values)

        elif kwarg == "start":
            start.append(values)

    print(ticks, start)


fn1(ticks=["IBM", "AAPL"], start="2")

output

 # python test123.py
[['IBM', 'AAPL']] ['2']

In the output I see that you want to get the passed kwarg value added to the array, but in the source code you are iterating over it. Not sure what exactly you are looking for, so I've done it by getting the desired output :)

Alexandr Shurigin
  • 3,921
  • 1
  • 13
  • 25