84

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']))
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abou Menah
  • 947
  • 1
  • 6
  • 9

7 Answers7

136

Well, a quote for the dictionary key is needed.

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

joar
  • 15,077
  • 1
  • 29
  • 54
M. Leung
  • 1,621
  • 1
  • 9
  • 9
  • 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 '17 at 07:25
  • 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 '17 at 07: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 '17 at 07: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 '23 at 17:26
49

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mark Langford
  • 527
  • 4
  • 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 06 '17 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. – Mark Langford Dec 20 '17 at 16:27
  • 2
    You could use the `format_map` function https://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 '19 at 08:02
  • 2
    @dbow is there any difference between `.format_map(dict)` and `.format(**dict)`? – MichaelChirico Mar 11 '20 at 09: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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ashwani Singh
  • 876
  • 11
  • 10
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Christian König
  • 3,437
  • 16
  • 28
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"]}'.

pkuphy
  • 314
  • 2
  • 9
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))
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mariotomo
  • 9,438
  • 8
  • 47
  • 66
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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Federico Baù
  • 6,013
  • 5
  • 30
  • 38