Skip to content

Commit 39352a8

Browse files
committed
dict.keys() is nearly always useless.
1 parent 1d4192c commit 39352a8

35 files changed

+66
-116
lines changed

doc/sphinxext/gen_gallery.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ def gen_gallery(app, doctree):
152152
fh.write(content)
153153

154154
for key in app.builder.status_iterator(
155-
iter(thumbnails.keys()), "generating thumbnails... ",
155+
iter(thumbnails), "generating thumbnails... ",
156156
length=len(thumbnails)):
157157
if out_of_date(key, thumbnails[key]):
158158
image.thumbnail(key, thumbnails[key], 0.3)

doc/sphinxext/gen_rst.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,7 @@ def generate_example_rst(app):
5151
relpath = os.path.split(root)[-1]
5252
datad.setdefault(relpath, []).append((fullpath, fname, contents))
5353

54-
subdirs = list(datad.keys())
55-
subdirs.sort()
54+
subdirs = sorted(datad)
5655

5756
fhindex = open(os.path.join(exampledir, 'index.rst'), 'w')
5857
fhindex.write("""\

examples/pylab_examples/fancybox_demo2.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@
88
fig1 = plt.figure(1, (4/1.5, figheight/1.5))
99
fontsize = 0.3 * 72
1010

11-
for i, stylename in enumerate(sorted(styles.keys())):
12-
fig1.text(0.5, (spacing * (float(len(styles)) - i) - 0.5)/figheight, stylename,
11+
for i, stylename in enumerate(sorted(styles)):
12+
fig1.text(0.5, (spacing * (len(styles) - i) - 0.5) / figheight, stylename,
1313
ha="center",
1414
size=fontsize,
1515
transform=fig1.transFigure,
1616
bbox=dict(boxstyle=stylename, fc="w", ec="k"))
17-
plt.draw()
17+
1818
plt.show()

examples/statistics/bxp_demo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
stats[n]['med'] = np.median(data)
3333
stats[n]['mean'] *= 2
3434

35-
print(stats[0].keys())
35+
print(list(stats[0]))
3636

3737
fs = 10 # fontsize
3838

examples/units/basic_units.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ def __get__(self, obj, objtype=None):
1717
return self.proxy_type(self.fn_name, obj)
1818

1919

20-
class TaggedValueMeta (type):
20+
class TaggedValueMeta(type):
2121
def __init__(cls, name, bases, dict):
22-
for fn_name in cls._proxies.keys():
22+
for fn_name in cls._proxies:
2323
try:
2424
dummy = getattr(cls, fn_name)
2525
except AttributeError:

examples/user_interfaces/toolmanager.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,18 +24,16 @@ class ListTools(ToolBase):
2424

2525
def trigger(self, *args, **kwargs):
2626
print('_' * 80)
27-
print("{0:12} {1:45} {2}".format('Name (id)',
28-
'Tool description',
29-
'Keymap'))
27+
print("{0:12} {1:45} {2}".format(
28+
'Name (id)', 'Tool description', 'Keymap'))
3029
print('-' * 80)
3130
tools = self.toolmanager.tools
32-
for name in sorted(tools.keys()):
31+
for name in sorted(tools):
3332
if not tools[name].description:
3433
continue
3534
keys = ', '.join(sorted(self.toolmanager.get_tool_keymap(name)))
36-
print("{0:12} {1:45} {2}".format(name,
37-
tools[name].description,
38-
keys))
35+
print("{0:12} {1:45} {2}".format(
36+
name, tools[name].description, keys))
3937
print('_' * 80)
4038
print("Active Toggle tools")
4139
print("{0:12} {1:45}".format("Group", "Active"))

lib/matplotlib/__init__.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -916,8 +916,9 @@ def __setitem__(self, key, val):
916916
raise ValueError("Key %s: %s" % (key, str(ve)))
917917
dict.__setitem__(self, key, cval)
918918
except KeyError:
919-
raise KeyError('%s is not a valid rc parameter.\
920-
See rcParams.keys() for a list of valid parameters.' % (key,))
919+
raise KeyError(
920+
'%s is not a valid rc parameter. See rcParams.keys() for a '
921+
'list of valid parameters.' % (key,))
921922

922923
def __getitem__(self, key):
923924
inverse_alt = None
@@ -974,7 +975,7 @@ def values(self):
974975
"""
975976
Return values in order of sorted keys.
976977
"""
977-
return [self[k] for k in self.keys()]
978+
return [self[k] for k in self]
978979

979980
def find_all(self, pattern):
980981
"""

lib/matplotlib/afm.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -199,10 +199,9 @@ def _parse_char_metrics(fh):
199199
if line.startswith('EndCharMetrics'):
200200
return ascii_d, name_d
201201
# Split the metric line into a dictonary, keyed by metric identifiers
202-
vals = filter(lambda s: len(s) > 0, line.split(';'))
203-
vals = dict(map(lambda s: tuple(s.strip().split(' ', 1)), vals))
202+
vals = dict(s.strip().split(' ', 1) for s in line.split(';') if s)
204203
# There may be other metrics present, but only these are needed
205-
if any([id not in vals.keys() for id in ('C', 'WX', 'N', 'B')]):
204+
if not {'C', 'WX', 'N', 'B'}.issubset(vals):
206205
raise RuntimeError('Bad char metrics line: %s' % line)
207206
num = _to_int(vals['C'])
208207
wx = _to_float(vals['WX'])

lib/matplotlib/animation.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def reset_available_writers(self):
108108
def list(self):
109109
''' Get a list of available MovieWriters.'''
110110
self.ensure_not_dirty()
111-
return list(self.avail.keys())
111+
return list(self.avail)
112112

113113
def is_available(self, name):
114114
'''Check if given writer is available by name.

lib/matplotlib/axes/_base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2942,7 +2942,7 @@ def set_xscale(self, value, **kwargs):
29422942
"""
29432943
# If the scale is being set to log, clip nonposx to prevent headaches
29442944
# around zero
2945-
if value.lower() == 'log' and 'nonposx' not in kwargs.keys():
2945+
if value.lower() == 'log' and 'nonposx' not in kwargs:
29462946
kwargs['nonposx'] = 'clip'
29472947

29482948
g = self.get_shared_x_axes()
@@ -3222,7 +3222,7 @@ def set_yscale(self, value, **kwargs):
32223222
"""
32233223
# If the scale is being set to log, clip nonposy to prevent headaches
32243224
# around zero
3225-
if value.lower() == 'log' and 'nonposy' not in kwargs.keys():
3225+
if value.lower() == 'log' and 'nonposy' not in kwargs:
32263226
kwargs['nonposy'] = 'clip'
32273227

32283228
g = self.get_shared_y_axes()

lib/matplotlib/backend_tools.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -618,7 +618,7 @@ def update_view(self):
618618
cur_view = home_views[a]
619619
a._set_view(cur_view)
620620

621-
if set(all_axes).issubset(pos.keys()):
621+
if set(all_axes).issubset(pos):
622622
for a in all_axes:
623623
# Restore both the original and modified positions
624624
a.set_position(pos[a][0], 'original')

lib/matplotlib/backends/backend_pgf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -424,7 +424,7 @@ def __init__(self, figure, fh, dummy=False):
424424
if dummy:
425425
# dummy==True deactivate all methods
426426
nop = lambda *args, **kwargs: None
427-
for m in RendererPgf.__dict__.keys():
427+
for m in RendererPgf.__dict__:
428428
if m.startswith("draw_"):
429429
self.__dict__[m] = nop
430430
else:

lib/matplotlib/category.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def _set_seq_locs(self, data, value):
8686
new_s = [d for d in np.unique(strdata) if d not in self.seq]
8787
for ns in new_s:
8888
self.seq.append(ns)
89-
if ns in UnitData.spdict.keys():
89+
if ns in UnitData.spdict:
9090
self.locs.append(UnitData.spdict[ns])
9191
else:
9292
self.locs.append(value)

lib/matplotlib/cm.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ def get_cmap(name=None, lut=None):
170170
else:
171171
raise ValueError(
172172
"Colormap %s is not recognized. Possible values are: %s"
173-
% (name, ', '.join(sorted(cmap_d.keys()))))
173+
% (name, ', '.join(sorted(cmap_d))))
174174

175175

176176
class ScalarMappable(object):

lib/matplotlib/dates.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -958,8 +958,7 @@ def __init__(self, tz=None, minticks=5, maxticks=None,
958958
# Assume we were given an integer. Use this as the maximum
959959
# number of ticks for every frequency and create a
960960
# dictionary for this
961-
self.maxticks = dict(zip(self._freqs,
962-
[maxticks] * len(self._freqs)))
961+
self.maxticks = dict.fromkeys(self._freqs, maxticks)
963962
self.interval_multiples = interval_multiples
964963
self.intervald = {
965964
YEARLY: [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500,

lib/matplotlib/font_manager.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -891,11 +891,10 @@ def set_size(self, size):
891891
scale = font_scalings[size]
892892
except KeyError:
893893
raise ValueError(
894-
"Size is invalid. Valid font size are " + ", ".join(
895-
str(i) for i in font_scalings.keys()))
894+
"Size is invalid. Valid font size are "
895+
+ ", ".join(map(str, font_scalings)))
896896
else:
897897
size = scale * FontManager.get_default_size()
898-
899898
self._size = size
900899

901900
def set_file(self, file):

lib/matplotlib/markers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@
9999
# special-purpose marker identifiers:
100100
(TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN,
101101
CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN,
102-
CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE) = list(xrange(12))
102+
CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE) = xrange(12)
103103

104104
_empty_path = Path(np.empty((0, 2)))
105105

lib/matplotlib/mlab.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2487,8 +2487,8 @@ def makekey(row):
24872487
r1d = {makekey(row): i for i, row in enumerate(r1)}
24882488
r2d = {makekey(row): i for i, row in enumerate(r2)}
24892489

2490-
r1keys = set(r1d.keys())
2491-
r2keys = set(r2d.keys())
2490+
r1keys = set(r1d)
2491+
r2keys = set(r2d)
24922492

24932493
common_keys = r1keys & r2keys
24942494

lib/matplotlib/offsetbox.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def _get_packed_offsets(wd_list, total, sep, mode="fixed"):
6767
*mode* : packing mode. 'fixed', 'expand', or 'equal'.
6868
"""
6969

70-
w_list, d_list = list(zip(*wd_list))
70+
w_list, d_list = zip(*wd_list)
7171
# d_list is currently not used.
7272

7373
if mode == "fixed":
@@ -1183,7 +1183,7 @@ def _get_anchored_bbox(self, loc, bbox, parentbbox, borderpad):
11831183
"""
11841184
assert loc in range(1, 11) # called only internally
11851185

1186-
BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = list(xrange(11))
1186+
BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = xrange(11)
11871187

11881188
anchor_coefs = {UR: "NE",
11891189
UL: "NW",

lib/matplotlib/patches.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1840,10 +1840,7 @@ def _simpleprint_styles(_styles):
18401840
(stylename : styleclass), return a string rep of the list of keys.
18411841
Used to update the documentation.
18421842
"""
1843-
styles = "[ \'"
1844-
styles += "\' | \'".join(str(i) for i in sorted(_styles.keys()))
1845-
styles += "\' ]"
1846-
return styles
1843+
return "[{}]".format("|".join(map(" '{}' ".format, sorted(_styles))))
18471844

18481845

18491846
class _Style(object):

lib/matplotlib/pyplot.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2096,7 +2096,7 @@ def colormaps():
20962096
20972097
20982098
"""
2099-
return sorted(cm.cmap_d.keys())
2099+
return sorted(cm.cmap_d)
21002100

21012101

21022102
def _setup_pyplot_info_docstrings():

lib/matplotlib/style/core.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,6 @@ def update_nested_dict(main_dict, new_dict):
218218

219219
def reload_library():
220220
"""Reload style library."""
221-
global library, available
222-
library = update_user_library(_base_library)
223-
available[:] = library.keys()
221+
global library
222+
available[:] = library = update_user_library(_base_library)
224223
reload_library()

lib/matplotlib/table.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -520,7 +520,7 @@ def _update_positions(self, renderer):
520520
else:
521521
# Position using loc
522522
(BEST, UR, UL, LL, LR, CL, CR, LC, UC, C,
523-
TR, TL, BL, BR, R, L, T, B) = list(xrange(len(self.codes)))
523+
TR, TL, BL, BR, R, L, T, B) = xrange(len(self.codes))
524524
# defaults for center
525525
ox = (0.5 - w / 2) - l
526526
oy = (0.5 - h / 2) - b

lib/matplotlib/tests/test_arrow_patches.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def test_boxarrow():
4444

4545
fontsize = 0.3 * 72
4646

47-
for i, stylename in enumerate(sorted(styles.keys())):
47+
for i, stylename in enumerate(sorted(styles)):
4848
fig1.text(0.5, ((n - i) * spacing - 0.5)/figheight, stylename,
4949
ha="center",
5050
size=fontsize,

lib/matplotlib/tests/test_axes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2793,7 +2793,7 @@ def test_empty_eventplot():
27932793
def test_marker_styles():
27942794
fig = plt.figure()
27952795
ax = fig.add_subplot(111)
2796-
for y, marker in enumerate(sorted(matplotlib.markers.MarkerStyle.markers.keys(),
2796+
for y, marker in enumerate(sorted(matplotlib.markers.MarkerStyle.markers,
27972797
key=lambda x: str(type(x))+str(x))):
27982798
ax.plot((y % 2)*5 + np.arange(10)*10, np.ones(10)*10*y, linestyle='', marker=marker,
27992799
markersize=10+y/5, label=marker)

lib/matplotlib/tests/test_backend_pdf.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -124,11 +124,11 @@ def test_composite_image():
124124
plt.rcParams['image.composite_image'] = True
125125
with PdfPages(io.BytesIO()) as pdf:
126126
fig.savefig(pdf, format="pdf")
127-
assert len(pdf._file._images.keys()) == 1
127+
assert len(pdf._file._images) == 1
128128
plt.rcParams['image.composite_image'] = False
129129
with PdfPages(io.BytesIO()) as pdf:
130130
fig.savefig(pdf, format="pdf")
131-
assert len(pdf._file._images.keys()) == 2
131+
assert len(pdf._file._images) == 2
132132

133133

134134
@cleanup

lib/matplotlib/tests/test_cbook.py

Lines changed: 11 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -173,73 +173,36 @@ def test_form_each_dict(self):
173173

174174
def test_form_dict_keys(self):
175175
for res in self.std_results:
176-
keys = sorted(list(res.keys()))
177-
for key in keys:
178-
assert key in self.known_keys
176+
assert set(res) <= set(self.known_keys)
179177

180178
def test_results_baseline(self):
181179
res = self.std_results[0]
182-
for key in list(self.known_nonbootstrapped_res.keys()):
183-
if key != 'fliers':
184-
assert_statement = assert_approx_equal
185-
else:
186-
assert_statement = assert_array_almost_equal
187-
188-
assert_statement(
189-
res[key],
190-
self.known_nonbootstrapped_res[key]
191-
)
180+
for key, value in self.known_nonbootstrapped_res.items():
181+
assert_array_almost_equal(res[key], value)
192182

193183
def test_results_bootstrapped(self):
194184
results = cbook.boxplot_stats(self.data, bootstrap=10000)
195185
res = results[0]
196-
for key in list(self.known_bootstrapped_ci.keys()):
197-
assert_approx_equal(
198-
res[key],
199-
self.known_bootstrapped_ci[key]
200-
)
186+
for key, value in self.known_bootstrapped_ci.items():
187+
assert_approx_equal(res[key], value)
201188

202189
def test_results_whiskers_float(self):
203190
results = cbook.boxplot_stats(self.data, whis=3)
204191
res = results[0]
205-
for key in list(self.known_whis3_res.keys()):
206-
if key != 'fliers':
207-
assert_statement = assert_approx_equal
208-
else:
209-
assert_statement = assert_array_almost_equal
210-
211-
assert_statement(
212-
res[key],
213-
self.known_whis3_res[key]
214-
)
192+
for key, value in self.known_whis3_res.items():
193+
assert_array_almost_equal(res[key], value)
215194

216195
def test_results_whiskers_range(self):
217196
results = cbook.boxplot_stats(self.data, whis='range')
218197
res = results[0]
219-
for key in list(self.known_res_range.keys()):
220-
if key != 'fliers':
221-
assert_statement = assert_approx_equal
222-
else:
223-
assert_statement = assert_array_almost_equal
224-
225-
assert_statement(
226-
res[key],
227-
self.known_res_range[key]
228-
)
198+
for key, value in self.known_res_range.items():
199+
assert_array_almost_equal(res[key], value)
229200

230201
def test_results_whiskers_percentiles(self):
231202
results = cbook.boxplot_stats(self.data, whis=[5, 95])
232203
res = results[0]
233-
for key in list(self.known_res_percentiles.keys()):
234-
if key != 'fliers':
235-
assert_statement = assert_approx_equal
236-
else:
237-
assert_statement = assert_array_almost_equal
238-
239-
assert_statement(
240-
res[key],
241-
self.known_res_percentiles[key]
242-
)
204+
for key, value in self.known_res_percentiles.items():
205+
assert_array_almost_equal(res[key], value)
243206

244207
def test_results_withlabels(self):
245208
labels = ['Test1', 2, 'ardvark', 4]

0 commit comments

Comments
 (0)