@@ -110,8 +110,10 @@ def _index_list(
110110 else :
111111 if isinstance (key_or_list , str ):
112112 return [(key_or_list , ASCENDING )]
113- if isinstance (key_or_list , abc .ItemsView ):
114- return list (key_or_list )
113+ elif isinstance (key_or_list , abc .ItemsView ):
114+ return list (key_or_list ) # type: ignore[arg-type]
115+ elif isinstance (key_or_list , abc .Mapping ):
116+ return list (key_or_list .items ())
115117 elif not isinstance (key_or_list , (list , tuple )):
116118 raise TypeError ("if no direction is specified, key_or_list must be an instance of list" )
117119 values : list [tuple [str , int ]] = []
@@ -127,33 +129,40 @@ def _index_document(index_list: _IndexList) -> SON[str, Any]:
127129
128130 Takes a list of (key, direction) pairs.
129131 """
130- if isinstance (index_list , abc .Mapping ):
132+ if not isinstance (index_list , ( list , tuple , abc .Mapping ) ):
131133 raise TypeError (
132- "passing a dict to sort/create_index/hint is not "
133- "allowed - use a list of tuples instead. did you "
134- "mean %r?" % list (index_list .items ())
134+ "must use a dictionary or a list of (key, direction) pairs, not: " + repr (index_list )
135135 )
136- elif not isinstance (index_list , (list , tuple )):
137- raise TypeError ("must use a list of (key, direction) pairs, not: " + repr (index_list ))
138136 if not len (index_list ):
139- raise ValueError ("key_or_list must not be the empty list " )
137+ raise ValueError ("key_or_list must not be empty" )
140138
141139 index : SON [str , Any ] = SON ()
142- for item in index_list :
143- if isinstance (item , str ):
144- item = (item , ASCENDING )
145- key , value = item
146- if not isinstance (key , str ):
147- raise TypeError ("first item in each key pair must be an instance of str" )
148- if not isinstance (value , (str , int , abc .Mapping )):
149- raise TypeError (
150- "second item in each key pair must be 1, -1, "
151- "'2d', or another valid MongoDB index specifier."
152- )
153- index [key ] = value
140+
141+ if isinstance (index_list , abc .Mapping ):
142+ for key in index_list :
143+ value = index_list [key ]
144+ _validate_index_key_pair (key , value )
145+ index [key ] = value
146+ else :
147+ for item in index_list :
148+ if isinstance (item , str ):
149+ item = (item , ASCENDING )
150+ key , value = item
151+ _validate_index_key_pair (key , value )
152+ index [key ] = value
154153 return index
155154
156155
156+ def _validate_index_key_pair (key : Any , value : Any ) -> None :
157+ if not isinstance (key , str ):
158+ raise TypeError ("first item in each key pair must be an instance of str" )
159+ if not isinstance (value , (str , int , abc .Mapping )):
160+ raise TypeError (
161+ "second item in each key pair must be 1, -1, "
162+ "'2d', or another valid MongoDB index specifier."
163+ )
164+
165+
157166def _check_command_response (
158167 response : _DocumentOut ,
159168 max_wire_version : Optional [int ],
0 commit comments