Skip to content

Commit 68e832a

Browse files
committed
ENH: add helpers to merge extra data into a cycler instance
From private discussions with @WeatherGod
1 parent 60f4da3 commit 68e832a

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

cycler.py

+56
Original file line numberDiff line numberDiff line change
@@ -558,3 +558,59 @@ def _cycler(label, itr):
558558
itr = (v[lab] for v in itr)
559559

560560
return Cycler._from_iter(label, itr)
561+
562+
563+
def from_iter_of_dicts(inp):
564+
"""Construct a summation-only cycler from a list of dicts
565+
566+
Given an iterable of dictionaries (such as you would get from
567+
iterating over a `Cycler`) and constructs a new `Cycler`.
568+
569+
The following are equivalent ::
570+
571+
from_iter_of_dicts(list(c)) == c.simplify()
572+
573+
Parameters
574+
----------
575+
inp : Iterable[Mapping[Any, Any]]
576+
An iterable of dictionaries. All must have the same keys.
577+
578+
Returns
579+
-------
580+
ret : Cycler
581+
"""
582+
# TODO better validation that all keys match, not just using
583+
# the keys from the first entry
584+
# TODO deal with empty list correctly
585+
inp = list(inp)
586+
return reduce(add, (cycler(k, [_[k] for _ in inp]) for k in inp[0]))
587+
588+
589+
def merge_suplemental(source, indx_key, sumplemental_data):
590+
"""Update a cycler with some supplemental data
591+
592+
Given a cycler, add extra keys to each entry based
593+
on the value of ``index_key`` in that entry.
594+
595+
Parameters
596+
----------
597+
source : Cycler
598+
The cycler to augment.
599+
600+
indx_key : Any
601+
Must be one of the keys in ``source``
602+
603+
sumplemental_data : Mapping[Any, Any]
604+
A mapping between the values of ``index_key`` in ``source``
605+
and mappings of additional keys and values.
606+
607+
Each mapping must have the same set of keys.
608+
609+
Returns
610+
-------
611+
ret : Cycler
612+
613+
"""
614+
return (source +
615+
from_iter_of_dicts(sumplemental_data[v[indx_key]]
616+
for v in source))

0 commit comments

Comments
 (0)