Python dictionary formatted output
Formatting Python Dictionary Output
In Python, a dictionary is a data type that maps keys to values. Since the keys and values in a dictionary can be any object type, they need to be formatted when outputting to make them easier to read and understand. This article will explain how to format dictionary output using Python string formatting and dictionary object methods.
1. Basic Example
The following is a basic dictionary formatting example:
person = {'name': 'Alice', 'age': 25, 'gender': 'female'}
print('{name} is a {age}-year-old {gender}.'.format(**person))
The output is:
Alice is a 25-year-old female.
As you can see, curly braces {}
are used in the output string to indicate the values to be filled in. Similarly, the format() method is used for formatting output. This method uses string formatting and often uses positional and keyword arguments for assignment.
In dictionary formatting, use **person
to convert the dictionary object person into a keyword argument and pass it to the format() method.
2. Key Formatting
In dictionary formatting, you can format the keys. The following is an example of formatting a dictionary key:
person = {'name': 'Alice', 'age': 25, 'gender': 'female'}
print('{name!r} is a {age}-year-old {gender}.'.format(**person))
The output is:
'Alice' is a 25-year-old female.
In the output string, the !r
format specifier is used to indicate that the key should be converted using the repr() function (displaying the keyword representation of the string), resulting in the string “Alice”.
Similarly, other format specifiers can be used to indicate that a key needs to be converted:
Format Specifier | Conversion Method |
---|---|
s | Convert using str() function |
r | Convert using repr() function |
The following is an example of using !s
to format a key:
person = {'name': 'Alice', 'age': 25, 'gender': 'female'}
print('{name!s} is a {age}-year-old {gender}.'.format(**person))
The output is:
Alice is a 25-year-old female.
3. Formatting Values
In dictionary formatting output, you can also format values. The following is an example of formatting a dictionary value:
person = {'name': 'Alice', 'age': 25, 'gender': 'female'}
print('{name} is a {age:d}-year-old {gender}.'.format(**person))
The output is:
Alice is a 25-year-old female.
In the output string, the format specifier :d
is used to indicate that the value should be output as a decimal integer.
Similarly, other format specifiers can be used to indicate the need for value conversion:
Format Specifier | Conversion Method |
---|---|
b | Use the bin() function to convert an integer to binary representation |
c | Convert an integer to its Unicode equivalent Characters |
d | Decimal integer |
o | Octal integer |
x | Hexadecimal integer (lowercase letters) |
X | Hexadecimal integer (uppercase letters) |
e | Floating point numbers using scientific notation, lowercase letters e |
E | Floating point numbers using scientific notation, uppercase letters E |
f | Floating point number, retains 6 decimal places |
F | Floating point number, same as f |
g | Automatically selects whether to use f or e format depending on the value size |
G | Automatically selects whether to use F or E format depending on the value size |
n | Floating point number, same as g, but inserts comma separators based on locale settings |
The following is an example using :d
Example of formatting a value using format specifiers:
person = {'name': 'Alice', 'age': 25, 'money': 1234567}
print('{name} is a {age}-year-old girl, and she has ${money:,d}.'.format(**person))
The output is:
Alice is a 25-year-old girl, and she has $1,234,567.
In the output string, the format specifier :,d
is used to indicate that the value should be formatted as an integer with a thousands separator.
Similarly, you can use other format specifiers to indicate that a value needs to be converted:
- Use the
:b
format specifier to convert a value to binary; - Use the
:o
format specifier to convert a value to octal; - Use the
:x
or:X
format specifier to convert a value to hexadecimal; - Use the
:e
or:E
format specifier to convert a value to scientific notation; - Use the
:f
or:F
format specifier to convert a value to a floating-point number; - Use the
:g
or:G
format specifier to convert a value to floating-point. Format specifiers automatically convert values to floating-point or scientific notation, automatically selecting the appropriate format based on the value’s size. - Use the
:n
format specifier to convert a value to a floating-point number with thousands separators.
In addition, you can use format options such as position, width, and padding to further format the output.
4. Custom Formatting
With dictionary-formatted output, you can customize the output to a specific format. The following is an example of a custom output format:
person = {'name': 'Alice', 'age': 25, 'money': 1234567}
print('{name:10} is a {age}-year-old girl, and she has ${money:,d}.'.format(**person))
The output is:
Alice is a 25-year-old girl, and she has $1,234,567.
In the output string, the format specifier :10
is used to indicate that the value should be padded to a total width of 10. In this case, the length of “Alice” is 5, so the remaining 5 characters are padded with spaces. Similarly, you can use :
followed by other options to customize the output format.
5. f-strings Formatting (Python 3.6+)
Beginning with Python 3.6, a new string formatting method, f-strings, was introduced. f-strings allow you to simply prefix a string with f
to indicate that it is an f-string. The expression enclosed in curly braces {}
will be automatically evaluated and inserted into the string.
The following is an example of using f-strings to format dictionary output:
person = {'name': 'Alice', 'age': 25, 'money': 1234567}
print(f"{person['name']} is a {person['age']}-year-old girl, and she has ${person['money']:,d}.")
The output is the same as the previous example:
Alice is a 25-year-old girl, and she has $1,234,567.
In f-strings, you can use expressions enclosed in curly braces {}
to directly access dictionary keys without using .format(**person)
F-strings also allow for additional functionality, such as expressions and function calls, making string formatting more flexible and convenient.
Conclusion
In Python, you can use string formatting and dictionary methods to format and output dictionaries. By formatting keys and values, and customizing the format, you can output dictionary information in a more intuitive and readable manner. Furthermore, starting with Python 3.6, you can also use f-strings for dictionary formatting, making string formatting even more concise and convenient. In daily development, choosing different formatting methods based on your needs can greatly improve code readability and maintainability.