Skip to content

Commit

Permalink
Support conversion of NamedList to/from a regular dict.
Browse files Browse the repository at this point in the history
  • Loading branch information
LTLA committed Nov 13, 2023
1 parent 0ba0912 commit acf7630
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
30 changes: 27 additions & 3 deletions src/biocutils/NamedList.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Sequence, Optional, Iterable, Union, Any
from typing import Sequence, Optional, Iterable, Union, Any, Dict
from copy import deepcopy

from .Names import Names
Expand All @@ -15,16 +15,28 @@ class NamedList(list):
a list, so it can be indexed as usual by integer positions or slices.
"""

def __init__(self, iterable: Optional[Iterable] = None, names: Optional[Names] = None):
def __init__(self, iterable: Optional[Union[Iterable, Dict]] = None, names: Optional[Names] = None):
"""
Args:
iterable:
Some iterable object. Alternatively None, for an empty list.
Some iterable object.
Alternatively, a dictionary where the keys are strings.
Alternatively None, for an empty list.
names:
List of names. This should have same length as ``iterable``.
If None, defaults to an empty list.
Ignored if ``iterable`` is a dictionary, in which case the
keys are used directly as the names.
"""
if isinstance(iterable, dict):
original = iterable
iterable = original.values()
names = (str(y) for y in original.keys())

if iterable is None:
super().__init__()
else:
Expand Down Expand Up @@ -252,6 +264,18 @@ def __deepcopy__(self, memo=None, _nil=[]) -> "NamedList":
"""
return NamedList(deepcopy(self, memo, _nil), names=deepcopy(self_names, memo, _nil))

def as_dict(self) -> dict[str, Any]:
"""
Returns:
A dictionary where the keys are the names and the values are the
list elements. Only the first occurrence of each name is returned.
"""
output = {}
for i, n in enumerate(self._names):
if n not in output:
output[n] = self[i]
return output


@subset_sequence.register
def _subset_sequence_NamedList(x: NamedList, indices: Sequence[int]) -> NamedList:
Expand Down
9 changes: 9 additions & 0 deletions tests/test_NamedList.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,15 @@ def test_NamedList_basics():
assert z.get_names() == [ "a", "b", "c", "d" ]


def test_NamedList_dict():
x = NamedList([1,2,3,4], names=['a', 'b', 'c', 'd'])
assert x.as_dict() == { "a": 1, "b": 2, "c": 3, "d": 4 }

x = NamedList({ "c": 4, "d": 5, 23: 99 })
assert x.get_names() == [ "c", "d", "23" ]
assert x == [ 4, 5, 99 ]


def test_NamedList_setitem():
x = NamedList([1,2,3,4], names=["A", "B", "C", "D"])
x[0] = None
Expand Down

0 comments on commit acf7630

Please sign in to comment.