87

How can I do this format with a Python 3.6 F-String?

person = {'name': 'Jenne', 'age': 23}

print('My name {0[name]} and my age {1[age]}'.format(person, person))
print('My name {0} and my age {1}'.format(person['name'], person['age']))
0

7 Answers 7

140

Well, a quote for the dictionary key is needed.

f'My name {person["name"]} and my age {person["age"]}'

4
  • 42
    Just use the different quotes between a whole string and items. If you quote the string in double quotes, use single quotes for the keys. Both single quotes and double quotes act the same function in python.
    – M. Leung
    Apr 19, 2017 at 7:25
  • 1
    Thanks what about that? print('My name is {name} and my age is {age} and my salary is {salary}.'.format(**person))
    – Abou Menah
    Apr 19, 2017 at 7:26
  • 3
    That is the str.format() method , the different between f-string and str.format is in how index lookups are performed, as you have to quote the key from dictionary in f-string, but auto converted from index value to the string in str.format()
    – M. Leung
    Apr 19, 2017 at 7:35
  • In Python 3.12+, you may use the same quotation marks, e.g., f'My name {person['name']} and my age {person['age']}'
    – Arn
    Aug 21 at 17:26
51

Depending on the number of contributions your dictionary makes to a given string, you might consider using .format(**dict) instead to make it more readable, even though it doesn't have the terse elegance of an f-string.

>>> person = {'name': 'Jenne', 'age': 23}
>>> print('My name is {name} and my age is {age}.'.format(**person))

Output:

My name is Jenne and my age is 23.

While this option is situational, you might like avoiding a snarl up of quotes and double quotes.

4
  • 3
    The question is about Python 3.6 f-strings explicitly, while you explain your answer clearly, this is not about what is being asked.
    – jpoppe
    Dec 6, 2017 at 15:13
  • 7
    true enough, I wrote this comment having recently put an f string in some of my own work like this: f'some text {mydict['mydumbmistake']} more text' vs f'some text {mydict["thisworks"]} more text' and visually the error was hard for me to spot (maybe I'm just rubbish), so love f strings as I do, its one place where the old style feels ligher on its feet and less chance of a dumbo like myself making yet another error. Dec 20, 2017 at 16:27
  • 2
    You could use the format_map function docs.python.org/3/library/stdtypes.html#str.format_map like this print('My name is {name} and my age is {age}.'.format_map(person))
    – dbow
    May 20, 2019 at 8:02
  • 2
    @dbow is there any difference between .format_map(dict) and .format(**dict)? Mar 11, 2020 at 9:19
26

Both of the below statements will work on Python 3.6 onward:

  1. print(f'My name {person["name"]} and my age {person["age"]}')
  2. print(f"My name {person['name']} and my age {person['age']}")

Please mind the single ' and double " quotes in the above statements, as placing them wrong will give a syntax error.

6

The string pkuphy posted is correct, and you have to use quotes to access the dictionary:

f'My name {person["name"]} and my age {person["age"]}'

Your original string works for the str.format()-function:

>>> person = {'name': 'Jenne', 'age': 23}
>>> print('My name is {person[name]} and my age is {person[age]}.'.format(person=person))

Output:

My name is Jenne and my age is 23.

The first person references all occurrences in the format-string, the second gives the variable to fill in.

4

This will work.

f'My name {person["name"]} and my age {person["age"]}'

if name is a property of obj, f'name is {obj[name]}', but for a dict as in this question, you can direct access the key f'name is {person["name"]}'.

3
  • error so that is why i am asking: f'My name {person[name]} and my age {person[age]}' NameError: name 'name' is not defined
    – Abou Menah
    Apr 19, 2017 at 6:46
  • 1
    Did you enclose name and age in parentheses as proposed?
    – ffi
    Jun 8, 2021 at 13:30
  • Also note that this will not work in Python 3.5 or lower. F-strings were introduced in Python 3.6.
    – Spartacus
    Mar 28, 2022 at 17:45
2

You have one object alone, which does not help understanding how things work. Let's build a more complete example.

person0 = {'name': 'Jenne', 'age': 23}
person1 = {'name': 'Jake', 'age': 29}
person2 = {'name': 'John', 'age': 31}
places = ['Naples', 'Marrakech', 'Cape Town']

print('''My name {0[name]} and my age {0[age]},
your name {1[name]} and your age {1[age]},
my favourite place {3[0]}'''.format(person0, person1, person2, places))

You can also access complete objects from the arguments list, like in:

print('{2}'.format(person0, person1, person2, places))

Or select attributes, even cascading:

print('{3.__class__.__name__}'.format(person0, person1, person2, places))
0

Quick stringification of a dictionary using an f-string without typing key manually

I was looking for a simple solution, in order to make a dictionary key, value pair a simple pair without the need to dig to each key of the dictionary.

person = {'name': 'Jenne', 'age': 23}
stringified_dict = ' '.join([f'{k.capitalize()} {v}' for k,v in person.items()])
print(f'In a Variable -->   {stringified_dict}')

# function
def stringify_dict(dict_val:dict) -> str:
    return ' '.join([f'{k.capitalize()} {v}' for k,v in dict_val.items()])

stringified_dict = stringify_dict({'name': 'Jenne', 'age': 23})
print(f'Using Function -->  {stringified_dict}')


# lambda
stringify_dict = lambda dict_val: ' '.join([f'{k.capitalize()} {v}' for k,v in dict_val.items()])
stringified_dict = stringify_dict({'name': 'Jenne', 'age': 23})
print(f'Using Lambda -->    {stringified_dict}')

Output

In a Variable -->   Name Jenne Age 23
Using Function -->  Name Jenne Age 23
Using Lambda -->    Name Jenne Age 23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.