Reputation: 27
"Hi -
Fairly rookie Python user and attempting some exercises in Python 3.1..
I was able to write a function taking LastName
, Country
as parameters and using **kwargs
to display values passed in for state
, salary
, taxrate
etc.
However, as a follow up I am trying to display keyword arguments regardless of the key - which is where I am getting stuck.
Looking for just the keyword arguments to be displayed rather than the passed in values
def myfunction(LastName, Country,**kwargs):
print('Name:',LastName)
print(Country)
result = ""
for arg in kwargs:
result = arg
return result
def main():
myfunction('Smith','USA',state="NV",salary="55k",taxrate='2.00')
if __name__ == '__main__':
main()
I am looking for an output like this:
Smith
USA
State
Salary
Taxrate
Upvotes: 0
Views: 67
Reputation: 387
If I interpret your question right, you may try this code:
# Returns a list in your desired format
def func(lastName, country, **kwargs):
ret = [lastName, country]
for key in kwargs:
ret.append(key.capitalize())
return ret
# Print
for i in func("", "", ...):
print(i)
It basically creates a base list to which it then appends the kwargs
keys. As you can see, kwargs
is a dict and can be used as one
Reminder: You should upgrade to the newest version of Python (3.8.1) which can be download here
Upvotes: 0
Reputation: 24691
For all intents and purposes, kwargs
is a dict. You can treat it as such:
def myfunction(last_name, country, **kwargs):
print('name =', last_name)
print('country =', country)
for key, value in kwargs.items():
print(key, '=', value)
>>> myfunction('Smith', 'USA', state="NV", salary="55k", taxrate='2.00')
name = Smith
country = USA
state = NV
salary = 55k
taxrate = 2.00
Upvotes: 1