How can I do a dictionary format with f-string in Python 3 .6?

Question:

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']))
Asked By: Abou Menah

||

Answers:

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"]}'.

Answered By: pkuphy

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.

Answered By: Christian König

Well, a quote for the dictionary key is needed.

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

Answered By: M. Leung

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.

Answered By: Mark Langford

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.

Answered By: yetis200

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))
Answered By: mariotomo

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
Answered By: Federico Baù
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.