Skip to content

Commit 4fce784

Browse files
mroeschkejreback
authored andcommitted
CLN: Replace comprehensions list/set/dict functions with corresponding symbols (#18383)
1 parent aec3347 commit 4fce784

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+160
-172
lines changed

asv_bench/benchmarks/frame_ctor.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,9 @@ def setup(self):
2323
self.some_dict = list(self.data.values())[0]
2424
self.dict_list = [dict(zip(self.columns, row)) for row in self.frame.values]
2525

26-
self.data2 = dict(
27-
((i, dict(((j, float(j)) for j in range(100)))) for i in
28-
range(2000)))
26+
self.data2 = {i: {j: float(j) for j in range(100)}
27+
for i in range(2000)}
28+
2929

3030
def time_frame_ctor_list_of_dict(self):
3131
DataFrame(self.dict_list)

asv_bench/benchmarks/packers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def _setup(self):
1818
self.N = 100000
1919
self.C = 5
2020
self.index = date_range('20000101', periods=self.N, freq='H')
21-
self.df = DataFrame(dict(('float{0}'.format(i), randn(self.N)) for i in range(self.C)), index=self.index)
21+
self.df = DataFrame({'float{0}'.format(i): randn(self.N) for i in range(self.C)}, index=self.index)
2222
self.df2 = self.df.copy()
2323
self.df2['object'] = [('%08x' % randrange((16 ** 8))) for _ in range(self.N)]
2424
self.remove(self.f)

asv_bench/benchmarks/replace.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ class replace_large_dict(object):
2323
def setup(self):
2424
self.n = (10 ** 6)
2525
self.start_value = (10 ** 5)
26-
self.to_rep = dict(((i, (self.start_value + i)) for i in range(self.n)))
26+
self.to_rep = {i: self.start_value + i for i in range(self.n)}
2727
self.s = Series(np.random.randint(self.n, size=(10 ** 3)))
2828

2929
def time_replace_large_dict(self):
@@ -35,8 +35,8 @@ class replace_convert(object):
3535

3636
def setup(self):
3737
self.n = (10 ** 3)
38-
self.to_ts = dict(((i, pd.Timestamp(i)) for i in range(self.n)))
39-
self.to_td = dict(((i, pd.Timedelta(i)) for i in range(self.n)))
38+
self.to_ts = {i: pd.Timestamp(i) for i in range(self.n)}
39+
self.to_td = {i: pd.Timedelta(i) for i in range(self.n)}
4040
self.s = Series(np.random.randint(self.n, size=(10 ** 3)))
4141
self.df = DataFrame({'A': np.random.randint(self.n, size=(10 ** 3)),
4242
'B': np.random.randint(self.n, size=(10 ** 3))})

doc/sphinxext/numpydoc/phantom_import.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ def import_phantom_module(xml_file):
6060
# Sort items so that
6161
# - Base classes come before classes inherited from them
6262
# - Modules come before their contents
63-
all_nodes = dict((n.attrib['id'], n) for n in root)
64-
63+
all_nodes = {n.attrib['id']: n for n in root}
64+
6565
def _get_bases(node, recurse=False):
6666
bases = [x.attrib['ref'] for x in node.findall('base')]
6767
if recurse:

pandas/_libs/tslibs/offsets.pyx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ from np_datetime cimport (pandas_datetimestruct,
3333
_MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL',
3434
'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
3535
_int_to_month = {(k + 1): v for k, v in enumerate(_MONTHS)}
36-
_month_to_int = dict((v, k) for k, v in _int_to_month.items())
36+
_month_to_int = {v: k for k, v in _int_to_month.items()}
3737

3838

3939
class WeekDay(object):

pandas/_libs/tslibs/resolution.pyx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ _ONE_HOUR = 60 * _ONE_MINUTE
5353
_ONE_DAY = 24 * _ONE_HOUR
5454

5555
DAYS = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']
56-
_weekday_rule_aliases = dict((k, v) for k, v in enumerate(DAYS))
56+
_weekday_rule_aliases = {k: v for k, v in enumerate(DAYS)}
5757

5858
_MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL',
5959
'AUG', 'SEP', 'OCT', 'NOV', 'DEC']

pandas/_version.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -141,11 +141,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
141141
if verbose:
142142
print("keywords are unexpanded, not using")
143143
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
144-
refs = set(r.strip() for r in refnames.strip("()").split(","))
144+
refs = {r.strip() for r in refnames.strip("()").split(",")}
145145
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
146146
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
147147
TAG = "tag: "
148-
tags = set(r[len(TAG):] for r in refs if r.startswith(TAG))
148+
tags = {r[len(TAG):] for r in refs if r.startswith(TAG)}
149149
if not tags:
150150
# Either we're using git < 1.8.3, or there really are no tags. We use
151151
# a heuristic: assume all version tags have a digit. The old git %d
@@ -154,7 +154,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
154154
# between branches and tags. By ignoring refnames without digits, we
155155
# filter out many common branch names like "release" and
156156
# "stabilization", as well as "HEAD" and "master".
157-
tags = set(r for r in refs if re.search(r'\d', r))
157+
tags = {r for r in refs if re.search(r'\d', r)}
158158
if verbose:
159159
print("discarding '{}', no digits".format(",".join(refs - tags)))
160160
if verbose:

pandas/core/common.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ def map_indices_py(arr):
347347
Returns a dictionary with (element, index) pairs for each element in the
348348
given array/list
349349
"""
350-
return dict((x, i) for i, x in enumerate(arr))
350+
return {x: i for i, x in enumerate(arr)}
351351

352352

353353
def union(*seqs):

pandas/core/dtypes/concat.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,7 @@ def _concat_datetimetz(to_concat, name=None):
459459
it is used in DatetimeIndex.append also
460460
"""
461461
# do not pass tz to set because tzlocal cannot be hashed
462-
if len(set(str(x.dtype) for x in to_concat)) != 1:
462+
if len({str(x.dtype) for x in to_concat}) != 1:
463463
raise ValueError('to_concat must have the same tz')
464464
tz = to_concat[0].tz
465465
# no need to localize because internal repr will not be changed
@@ -525,7 +525,7 @@ def convert_sparse(x, axis):
525525
if len(typs) == 1:
526526
# concat input as it is if all inputs are sparse
527527
# and have the same fill_value
528-
fill_values = set(c.fill_value for c in to_concat)
528+
fill_values = {c.fill_value for c in to_concat}
529529
if len(fill_values) == 1:
530530
sp_values = [c.sp_values for c in to_concat]
531531
indexes = [c.sp_index.to_int_index() for c in to_concat]

pandas/core/frame.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ def __init__(self, data=None, index=None, columns=None, dtype=None,
347347
elif isinstance(data, (np.ndarray, Series, Index)):
348348
if data.dtype.names:
349349
data_columns = list(data.dtype.names)
350-
data = dict((k, data[k]) for k in data_columns)
350+
data = {k: data[k] for k in data_columns}
351351
if columns is None:
352352
columns = data_columns
353353
mgr = self._init_dict(data, index, columns, dtype=dtype)
@@ -417,8 +417,7 @@ def _init_dict(self, data, index, columns, dtype=None):
417417
extract_index(list(data.values()))
418418

419419
# prefilter if columns passed
420-
data = dict((k, v) for k, v in compat.iteritems(data)
421-
if k in columns)
420+
data = {k: v for k, v in compat.iteritems(data) if k in columns}
422421

423422
if index is None:
424423
index = extract_index(list(data.values()))
@@ -3895,7 +3894,7 @@ def f(col):
38953894
return self._constructor_sliced(r, index=new_index,
38963895
dtype=r.dtype)
38973896

3898-
result = dict((col, f(col)) for col in this)
3897+
result = {col: f(col) for col in this}
38993898

39003899
# non-unique
39013900
else:
@@ -3906,7 +3905,7 @@ def f(i):
39063905
return self._constructor_sliced(r, index=new_index,
39073906
dtype=r.dtype)
39083907

3909-
result = dict((i, f(i)) for i, col in enumerate(this.columns))
3908+
result = {i: f(i) for i, col in enumerate(this.columns)}
39103909
result = self._constructor(result, index=new_index, copy=False)
39113910
result.columns = new_columns
39123911
return result
@@ -3984,7 +3983,7 @@ def _compare_frame_evaluate(self, other, func, str_rep, try_cast=True):
39843983
if self.columns.is_unique:
39853984

39863985
def _compare(a, b):
3987-
return dict((col, func(a[col], b[col])) for col in a.columns)
3986+
return {col: func(a[col], b[col]) for col in a.columns}
39883987

39893988
new_data = expressions.evaluate(_compare, str_rep, self, other)
39903989
return self._constructor(data=new_data, index=self.index,
@@ -3993,8 +3992,8 @@ def _compare(a, b):
39933992
else:
39943993

39953994
def _compare(a, b):
3996-
return dict((i, func(a.iloc[:, i], b.iloc[:, i]))
3997-
for i, col in enumerate(a.columns))
3995+
return {i: func(a.iloc[:, i], b.iloc[:, i])
3996+
for i, col in enumerate(a.columns)}
39983997

39993998
new_data = expressions.evaluate(_compare, str_rep, self, other)
40003999
result = self._constructor(data=new_data, index=self.index,

0 commit comments

Comments
 (0)