How can I do a dictionary format with f-string in Python 3 .6?
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']))
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.
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:
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