Skip to content

Commit 4168e0c

Browse files
alimcmaster1WillAyd
authored andcommitted
CLN: OrderedDict -> Dict (#30497)
1 parent 641051f commit 4168e0c

File tree

12 files changed

+40
-98
lines changed

12 files changed

+40
-98
lines changed

pandas/core/arrays/sparse/scipy_sparse.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
44
Currently only includes to_coo helpers.
55
"""
6-
from collections import OrderedDict
7-
86
from pandas.core.indexes.api import Index, MultiIndex
97
from pandas.core.series import Series
108

@@ -46,14 +44,13 @@ def get_indexers(levels):
4644
# labels_to_i[:] = np.arange(labels_to_i.shape[0])
4745

4846
def _get_label_to_i_dict(labels, sort_labels=False):
49-
""" Return OrderedDict of unique labels to number.
47+
""" Return dict of unique labels to number.
5048
Optionally sort by label.
5149
"""
5250
labels = Index(map(tuple, labels)).unique().tolist() # squish
5351
if sort_labels:
5452
labels = sorted(labels)
55-
d = OrderedDict((k, i) for i, k in enumerate(labels))
56-
return d
53+
return {k: i for i, k in enumerate(labels)}
5754

5855
def _get_index_subset_to_coord_dict(index, subset, sort_labels=False):
5956
ilabels = list(zip(*[index._get_level_values(i) for i in subset]))

pandas/core/groupby/generic.py

+9-8
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
These are user facing as the result of the ``df.groupby(...)`` operations,
66
which here returns a DataFrameGroupBy object.
77
"""
8-
from collections import OrderedDict, abc, defaultdict, namedtuple
8+
from collections import abc, defaultdict, namedtuple
99
import copy
1010
from functools import partial
1111
from textwrap import dedent
@@ -14,6 +14,7 @@
1414
TYPE_CHECKING,
1515
Any,
1616
Callable,
17+
Dict,
1718
FrozenSet,
1819
Iterable,
1920
List,
@@ -306,7 +307,7 @@ def _aggregate_multiple_funcs(self, arg):
306307

307308
arg = zip(columns, arg)
308309

309-
results = OrderedDict()
310+
results = {}
310311
for name, func in arg:
311312
obj = self
312313

@@ -443,7 +444,7 @@ def _get_index() -> Index:
443444
return self._reindex_output(result)
444445

445446
def _aggregate_named(self, func, *args, **kwargs):
446-
result = OrderedDict()
447+
result = {}
447448

448449
for name, group in self:
449450
group.name = name
@@ -1122,7 +1123,7 @@ def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame:
11221123
axis = self.axis
11231124
obj = self._obj_with_exclusions
11241125

1125-
result: OrderedDict = OrderedDict()
1126+
result: Dict[Union[int, str], Union[NDFrame, np.ndarray]] = {}
11261127
if axis != obj._info_axis_number:
11271128
for name, data in self:
11281129
fres = func(data, *args, **kwargs)
@@ -1139,7 +1140,7 @@ def _aggregate_item_by_item(self, func, *args, **kwargs) -> DataFrame:
11391140
# only for axis==0
11401141

11411142
obj = self._obj_with_exclusions
1142-
result: OrderedDict = OrderedDict()
1143+
result: Dict[Union[int, str], NDFrame] = {}
11431144
cannot_agg = []
11441145
for item in obj:
11451146
data = obj[item]
@@ -1877,7 +1878,7 @@ def _normalize_keyword_aggregation(kwargs):
18771878
Normalize user-provided "named aggregation" kwargs.
18781879
18791880
Transforms from the new ``Mapping[str, NamedAgg]`` style kwargs
1880-
to the old OrderedDict[str, List[scalar]]].
1881+
to the old Dict[str, List[scalar]]].
18811882
18821883
Parameters
18831884
----------
@@ -1895,11 +1896,11 @@ def _normalize_keyword_aggregation(kwargs):
18951896
Examples
18961897
--------
18971898
>>> _normalize_keyword_aggregation({'output': ('input', 'sum')})
1898-
(OrderedDict([('input', ['sum'])]), ('output',), [('input', 'sum')])
1899+
({'input': ['sum']}, ('output',), [('input', 'sum')])
18991900
"""
19001901
# Normalize the aggregation functions as Mapping[column, List[func]],
19011902
# process normally, then fixup the names.
1902-
# TODO: aggspec type: typing.OrderedDict[str, List[AggScalar]]
1903+
# TODO: aggspec type: typing.Dict[str, List[AggScalar]]
19031904
# May be hitting https://github.com/python/mypy/issues/5958
19041905
# saying it doesn't have an attribute __name__
19051906
aggspec = defaultdict(list)

pandas/core/indexes/multi.py

+5-11
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from collections import OrderedDict
21
import datetime
32
from sys import getsizeof
43
from typing import Hashable, List, Optional, Sequence, Union
@@ -1639,17 +1638,12 @@ def to_frame(self, index=True, name=None):
16391638
else:
16401639
idx_names = self.names
16411640

1642-
# Guarantee resulting column order
1641+
# Guarantee resulting column order - PY36+ dict maintains insertion order
16431642
result = DataFrame(
1644-
OrderedDict(
1645-
[
1646-
(
1647-
(level if lvlname is None else lvlname),
1648-
self._get_level_values(level),
1649-
)
1650-
for lvlname, level in zip(idx_names, range(len(self.levels)))
1651-
]
1652-
),
1643+
{
1644+
(level if lvlname is None else lvlname): self._get_level_values(level)
1645+
for lvlname, level in zip(idx_names, range(len(self.levels)))
1646+
},
16531647
copy=False,
16541648
)
16551649

pandas/io/formats/html.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
Module for formatting output data in HTML.
33
"""
44

5-
from collections import OrderedDict
65
from textwrap import dedent
76
from typing import IO, Any, Dict, Iterable, List, Mapping, Optional, Tuple, Union, cast
87

@@ -138,10 +137,9 @@ def _write_cell(
138137
else:
139138
start_tag = "<{kind}>".format(kind=kind)
140139

141-
esc: Union[OrderedDict[str, str], Dict]
142140
if self.escape:
143141
# escape & first to prevent double escaping of &
144-
esc = OrderedDict([("&", r"&amp;"), ("<", r"&lt;"), (">", r"&gt;")])
142+
esc = {"&": r"&amp;", "<": r"&lt;", ">": r"&gt;"}
145143
else:
146144
esc = {}
147145

pandas/tests/io/parser/test_common.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
specific classification into the other test modules.
44
"""
55
import codecs
6-
from collections import OrderedDict
76
import csv
87
from datetime import datetime
98
from io import BytesIO, StringIO
@@ -1316,9 +1315,7 @@ def test_float_parser(all_parsers):
13161315

13171316
def test_scientific_no_exponent(all_parsers):
13181317
# see gh-12215
1319-
df = DataFrame.from_dict(
1320-
OrderedDict([("w", ["2e"]), ("x", ["3E"]), ("y", ["42e"]), ("z", ["632E"])])
1321-
)
1318+
df = DataFrame.from_dict({"w": ["2e"], "x": ["3E"], "y": ["42e"], "z": ["632E"]})
13221319
data = df.to_csv(index=False)
13231320
parser = all_parsers
13241321

pandas/tests/reshape/merge/test_multi.py

+4-14
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from collections import OrderedDict
2-
31
import numpy as np
42
from numpy.random import randn
53
import pytest
@@ -474,17 +472,13 @@ def test_merge_datetime_index(self, klass):
474472
if klass is not None:
475473
on_vector = klass(on_vector)
476474

477-
expected = DataFrame(
478-
OrderedDict([("a", [1, 2, 3]), ("key_1", [2016, 2017, 2018])])
479-
)
475+
expected = DataFrame({"a": [1, 2, 3], "key_1": [2016, 2017, 2018]})
480476

481477
result = df.merge(df, on=["a", on_vector], how="inner")
482478
tm.assert_frame_equal(result, expected)
483479

484480
expected = DataFrame(
485-
OrderedDict(
486-
[("key_0", [2016, 2017, 2018]), ("a_x", [1, 2, 3]), ("a_y", [1, 2, 3])]
487-
)
481+
{"key_0": [2016, 2017, 2018], "a_x": [1, 2, 3], "a_y": [1, 2, 3]}
488482
)
489483

490484
result = df.merge(df, on=[df.index.year], how="inner")
@@ -788,17 +782,13 @@ def test_merge_datetime_index(self, box):
788782
if box is not None:
789783
on_vector = box(on_vector)
790784

791-
expected = DataFrame(
792-
OrderedDict([("a", [1, 2, 3]), ("key_1", [2016, 2017, 2018])])
793-
)
785+
expected = DataFrame({"a": [1, 2, 3], "key_1": [2016, 2017, 2018]})
794786

795787
result = df.merge(df, on=["a", on_vector], how="inner")
796788
tm.assert_frame_equal(result, expected)
797789

798790
expected = DataFrame(
799-
OrderedDict(
800-
[("key_0", [2016, 2017, 2018]), ("a_x", [1, 2, 3]), ("a_y", [1, 2, 3])]
801-
)
791+
{"key_0": [2016, 2017, 2018], "a_x": [1, 2, 3], "a_y": [1, 2, 3]}
802792
)
803793

804794
result = df.merge(df, on=[df.index.year], how="inner")

pandas/tests/reshape/test_pivot.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from collections import OrderedDict
21
from datetime import date, datetime, timedelta
32
from itertools import product
43

@@ -1044,7 +1043,7 @@ def test_pivot_columns_lexsorted(self):
10441043
assert pivoted.columns.is_monotonic
10451044

10461045
def test_pivot_complex_aggfunc(self):
1047-
f = OrderedDict([("D", ["std"]), ("E", ["sum"])])
1046+
f = {"D": ["std"], "E": ["sum"]}
10481047
expected = self.data.groupby(["A", "B"]).agg(f).unstack("B")
10491048
result = self.data.pivot_table(index="A", columns="B", aggfunc=f)
10501049

pandas/tests/util/test_validate_args.py

+2-11
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from collections import OrderedDict
2-
31
import pytest
42

53
from pandas.util._validators import validate_args
@@ -58,11 +56,7 @@ def test_not_all_defaults(i):
5856
r"in the pandas implementation of {func}\(\)".format(arg=bad_arg, func=_fname)
5957
)
6058

61-
compat_args = OrderedDict()
62-
compat_args["foo"] = 2
63-
compat_args["bar"] = -1
64-
compat_args["baz"] = 3
65-
59+
compat_args = {"foo": 2, "bar": -1, "baz": 3}
6660
arg_vals = (1, -1, 3)
6761

6862
with pytest.raises(ValueError, match=msg):
@@ -73,8 +67,5 @@ def test_validation():
7367
# No exceptions should be raised.
7468
validate_args(_fname, (None,), 2, dict(out=None))
7569

76-
compat_args = OrderedDict()
77-
compat_args["axis"] = 1
78-
compat_args["out"] = None
79-
70+
compat_args = {"axis": 1, "out": None}
8071
validate_args(_fname, (1, None), 2, compat_args)

pandas/tests/util/test_validate_args_and_kwargs.py

+3-14
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from collections import OrderedDict
2-
31
import pytest
42

53
from pandas.util._validators import validate_args_and_kwargs
@@ -52,9 +50,7 @@ def test_missing_args_or_kwargs(args, kwargs):
5250
bad_arg = "bar"
5351
min_fname_arg_count = 2
5452

55-
compat_args = OrderedDict()
56-
compat_args["foo"] = -5
57-
compat_args[bad_arg] = 1
53+
compat_args = {"foo": -5, bad_arg: 1}
5854

5955
msg = (
6056
r"the '{arg}' parameter is not supported "
@@ -68,11 +64,7 @@ def test_missing_args_or_kwargs(args, kwargs):
6864
def test_duplicate_argument():
6965
min_fname_arg_count = 2
7066

71-
compat_args = OrderedDict()
72-
compat_args["foo"] = None
73-
compat_args["bar"] = None
74-
compat_args["baz"] = None
75-
67+
compat_args = {"foo": None, "bar": None, "baz": None}
7668
kwargs = {"foo": None, "bar": None}
7769
args = (None,) # duplicate value for "foo"
7870

@@ -84,10 +76,7 @@ def test_duplicate_argument():
8476

8577
def test_validation():
8678
# No exceptions should be raised.
87-
compat_args = OrderedDict()
88-
compat_args["foo"] = 1
89-
compat_args["bar"] = None
90-
compat_args["baz"] = -2
79+
compat_args = {"foo": 1, "bar": None, "baz": -2}
9180
kwargs = {"baz": -2}
9281

9382
args = (1, None)

pandas/tests/util/test_validate_kwargs.py

+3-13
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from collections import OrderedDict
2-
31
import pytest
42

53
from pandas.util._validators import validate_bool_kwarg, validate_kwargs
@@ -11,9 +9,7 @@ def test_bad_kwarg():
119
good_arg = "f"
1210
bad_arg = good_arg + "o"
1311

14-
compat_args = OrderedDict()
15-
compat_args[good_arg] = "foo"
16-
compat_args[bad_arg + "o"] = "bar"
12+
compat_args = {good_arg: "foo", bad_arg + "o": "bar"}
1713
kwargs = {good_arg: "foo", bad_arg: "bar"}
1814

1915
msg = fr"{_fname}\(\) got an unexpected keyword argument '{bad_arg}'"
@@ -30,10 +26,7 @@ def test_not_all_none(i):
3026
r"in the pandas implementation of {func}\(\)".format(arg=bad_arg, func=_fname)
3127
)
3228

33-
compat_args = OrderedDict()
34-
compat_args["foo"] = 1
35-
compat_args["bar"] = "s"
36-
compat_args["baz"] = None
29+
compat_args = {"foo": 1, "bar": "s", "baz": None}
3730

3831
kwarg_keys = ("foo", "bar", "baz")
3932
kwarg_vals = (2, "s", None)
@@ -46,10 +39,7 @@ def test_not_all_none(i):
4639

4740
def test_validation():
4841
# No exceptions should be raised.
49-
compat_args = OrderedDict()
50-
compat_args["f"] = None
51-
compat_args["b"] = 1
52-
compat_args["ba"] = "s"
42+
compat_args = {"f": None, "b": 1, "ba": "s"}
5343

5444
kwargs = dict(f=None, b=1)
5545
validate_kwargs(_fname, kwargs, compat_args)

pandas/util/_validators.py

+7-10
Original file line numberDiff line numberDiff line change
@@ -84,15 +84,13 @@ def validate_args(fname, args, max_fname_arg_count, compat_args):
8484
The maximum number of arguments that the function `fname`
8585
can accept, excluding those in `args`. Used for displaying
8686
appropriate error messages. Must be non-negative.
87-
compat_args : Dict
88-
An ordered dictionary of keys and their associated default values.
87+
compat_args : dict
88+
A dictionary of keys and their associated default values.
8989
In order to accommodate buggy behaviour in some versions of `numpy`,
9090
where a signature displayed keyword arguments but then passed those
9191
arguments **positionally** internally when calling downstream
92-
implementations, an ordered dictionary ensures that the original
93-
order of the keyword arguments is enforced. Note that if there is
94-
only one key, a generic dict can be passed in as well.
95-
92+
implementations, a dict ensures that the original
93+
order of the keyword arguments is enforced.
9694
Raises
9795
------
9896
TypeError
@@ -168,10 +166,9 @@ def validate_args_and_kwargs(fname, args, kwargs, max_fname_arg_count, compat_ar
168166
The minimum number of arguments that the function `fname`
169167
requires, excluding those in `args`. Used for displaying
170168
appropriate error messages. Must be non-negative.
171-
compat_args: OrderedDict
172-
A ordered dictionary of keys that `kwargs` is allowed to
173-
have and their associated default values. Note that if there
174-
is only one key, a generic dict can be passed in as well.
169+
compat_args: dict
170+
A dictionary of keys that `kwargs` is allowed to
171+
have and their associated default values.
175172
176173
Raises
177174
------

0 commit comments

Comments
 (0)