Skip to content

Commit 218fadb

Browse files
Added article with minor enhancements
1 parent 0fb6153 commit 218fadb

File tree

1 file changed

+40
-13
lines changed

1 file changed

+40
-13
lines changed

docs/readability/not_using_dict_keys_when_formatting_strings.rst

+40-13
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
Not using dict keys when formatting strings
32
===========================================
43

@@ -7,7 +6,10 @@ When formatting a string with values from a dictionary, you can use the dictiona
76

87
.. code:: python
98
10-
person = {'first':'Tobin', 'age':20}
9+
person = {
10+
'first': 'Tobin',
11+
'age': 20
12+
}
1113
1214
1315
Anti-pattern
@@ -17,13 +19,30 @@ Here is an example of formatting the string with values from the person. This is
1719

1820
.. code:: python
1921
20-
person = {'first':'Tobin', 'age':20}
21-
print('{0} is {1} years old'.format(person['first'], person['age'])) # bad
22-
# >>> Tobin is 20 years old
22+
person = {
23+
'first': 'Tobin',
24+
'age':20
25+
}
26+
27+
print('{0} is {1} years old'.format(
28+
person['first'],
29+
person['age'])
30+
)
31+
# Output: Tobin is 20 years old
2332
24-
person = {'first':'Tobin', 'last': 'Brown', 'age':20}
25-
print('{0} {1} is {2} years old'.format(person['first'], person['last'], person['age'])) # bad
26-
# >>> Tobin Brown is 20 years old
33+
person = {
34+
'first': 'Tobin',
35+
'last': 'Brown',
36+
'age':20
37+
}
38+
39+
# Bad: we have to change the replacement fields within our string, once we add new values
40+
print('{0} {1} is {2} years old'.format(
41+
person['first'],
42+
person['last'],
43+
person['age'])
44+
) # bad
45+
# Output: Tobin Brown is 20 years old
2746
2847
2948
Best practice
@@ -33,13 +52,21 @@ By using the dictionary keys in the string we are formatting, the code is much m
3352

3453
.. code:: python
3554
36-
person = {'first':'Tobin', 'age':20}
55+
person = {
56+
'first': 'Tobin',
57+
'age':20
58+
}
59+
3760
print('{first} is {age} years old'.format(**person))
38-
# >>> Tobin is 20 years old
61+
# Output: Tobin is 20 years old
3962
40-
person = {'first':'Tobin', 'last': 'Brown', 'age':20}
63+
person = {
64+
'first':'Tobin',
65+
'last': 'Brown',
66+
'age':20
67+
}
4168
print('{first} {last} is {age} years old'.format(**person))
42-
# >>> Tobin Brown is 20 years old
69+
# Output: Tobin Brown is 20 years old
4370
4471
4572
Going even further, the same result can be achieved with your own objects by using ``obj.__dict__``.
@@ -59,4 +86,4 @@ Going even further, the same result can be achieved with your own objects by usi
5986
6087
person = Person('Tobin', 'Brown', 20)
6188
print(person)
62-
# >>> Tobin Brown is 20 years old
89+
# Output: Tobin Brown is 20 years old

0 commit comments

Comments
 (0)