|
42 | 42 | _default_index, |
43 | 43 | _asarray_tuplesafe, |
44 | 44 | _values_from_object, |
45 | | - _try_sort, |
46 | 45 | _maybe_match_name, |
47 | 46 | SettingWithCopyError, |
48 | 47 | _maybe_box_datetimelike, |
@@ -198,18 +197,9 @@ def __init__(self, data=None, index=None, dtype=None, name=None, |
198 | 197 | data = data.reindex(index, copy=copy) |
199 | 198 | data = data._data |
200 | 199 | elif isinstance(data, dict): |
201 | | - if index is None: |
202 | | - if isinstance(data, OrderedDict): |
203 | | - index = Index(data) |
204 | | - else: |
205 | | - index = Index(_try_sort(data)) |
206 | | - |
207 | | - try: |
208 | | - data = index._get_values_from_dict(data) |
209 | | - except TypeError: |
210 | | - data = ([data.get(i, np.nan) for i in index] |
211 | | - if data else np.nan) |
212 | | - |
| 200 | + data, index = self._init_from_dict(data, index, dtype) |
| 201 | + dtype = None |
| 202 | + copy = False |
213 | 203 | elif isinstance(data, SingleBlockManager): |
214 | 204 | if index is None: |
215 | 205 | index = data.index |
@@ -303,6 +293,43 @@ def _can_hold_na(self): |
303 | 293 |
|
304 | 294 | _index = None |
305 | 295 |
|
| 296 | + def _init_from_dict(self, data, index=None, dtype=None): |
| 297 | + """ |
| 298 | + Derive the "_data" and "index" attributes of a new Series from a |
| 299 | + dictionary input. |
| 300 | +
|
| 301 | + Parameters |
| 302 | + ---------- |
| 303 | + data : dict or dict-like |
| 304 | + Data used to populate the new Series |
| 305 | + index : Index or index-like, default None |
| 306 | + index for the new Series: if None, use dict keys |
| 307 | + dtype : dtype, default None |
| 308 | + dtype for the new Series: if None, infer from data |
| 309 | +
|
| 310 | + Returns |
| 311 | + ------- |
| 312 | + _data : BlockManager for the new Series |
| 313 | + index : index for the new Series |
| 314 | + """ |
| 315 | + # Looking for NaN in dict doesn't work ({np.nan : 1}[float('nan')] |
| 316 | + # raises KeyError), so we iterate the entire dict, and align |
| 317 | + if data: |
| 318 | + keys, values = zip(*compat.iteritems(data)) |
| 319 | + else: |
| 320 | + keys, values = [], [] |
| 321 | + # Input is now list-like, so rely on "standard" construction: |
| 322 | + s = Series(values, index=keys, dtype=dtype) |
| 323 | + # Now we just make sure the order is respected, if any |
| 324 | + if index is not None and not index.identical(keys): |
| 325 | + s = s.reindex(index) |
| 326 | + elif not isinstance(data, OrderedDict): |
| 327 | + try: |
| 328 | + s = s.sort_index() |
| 329 | + except TypeError: |
| 330 | + pass |
| 331 | + return s._data, s.index |
| 332 | + |
306 | 333 | def _set_axis(self, axis, labels, fastpath=False): |
307 | 334 | """ override generic, we want to set the _typ here """ |
308 | 335 |
|
|
0 commit comments