Home > Net >  How to do a **kwargs dictionary format with fstrings in python
How to do a **kwargs dictionary format with fstrings in python

Time:11-29

I was going through this python course and since I wanted to get used to fstrings as opposed to .format(), I used a fstring instead.

But all it does is return a syntax error. (It doesn't return any error if I take away the string type from "name")

def myfunc(**kwargs):
    print(kwargs)
    if "name" in kwargs:
        print(f"My name is {kwargs["name"]}")
    else:
        print("Not my name")

This on the other hand works just fine:

person = {"name": 'Jenne', "age": 23}
if "name" in person:
    print(f'My name {person["name"]} and my age {person["age"]}')
else:
    "not here"

If it helps I'm doing this on jupyter notebook

Side note: If I took away the string type from "name" it'll go through without any errors. Like this:

def myfunc(**kwargs):
    print(kwargs)
    if name in kwargs:
        print(f"My name is {kwargs[name]}")
    else:
        print("Not my name")

But if I try to use the function after that, it'll give me this error. Where it says name not defined.

myfunc(name = 'Jenne', age = 23)
{'name': 'Jenne', 'age': 23}
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-63-a9983a7b4600> in <module>
----> 1 myfunc(name = 'Jenne', age = 23)

<ipython-input-56-5814d7cb2131> in myfunc(**kwargs)
      1 def myfunc(**kwargs):
      2     print(kwargs)
----> 3     if name in kwargs:
      4         print(f"My name is {kwargs[name]}")
      5     else:

NameError: name 'name' is not defined

CodePudding user response:

You need to use different quote types e.g.:

def myfunc(**kwargs):
    print(kwargs)
    if "name" in kwargs:
        print(f'my name is {kwargs["name"]}')
    else:
        print("Not my name")
  • Related