Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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")
1 comments

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading