Skip to content

KeyedList

KeyedList

Bases: Generic[K, V]

A row that reads like a dict but points at a list instead of copying its values.

A KeyedList pairs a list of values with an index of the keys. You read it by key, as in row['qty'], the same way you read a dict. But the values are not copied into it. It adopts the list you give it. It can also share one index of keys with many other KeyedLists, which is what a table does with the column names of its rows.

Daffodil gives you its rows as KeyedLists when itermode is 'keyedlist', and from iter_klist() and iloc(). Each one points at a row of the table.

How it differs from a dict:

  • Writing to it writes to the list it adopted. If that list is a row of a Daf, the Daf changes. A dict row never changes the table.
  • values() returns the adopted list itself, not a copy. Use to_dict() for an independent copy.
  • Creating one is cheap if you give it an existing index. A dict copies every value in.
  • Keys must be unique, and keys and values must be the same length.

Ways to create one:

  • KeyedList(keys, values): adopts the values list. No copy.
  • KeyedList(hd, values): the same, but shares an hd that you already have, a dict of each key and its position. This is the fastest, and it is what Daf does for its rows: each row shares the hd of the Daf. Then row.hd is daf.hd.
  • KeyedList(a_dict): copies the values out of the dict. Slower than the forms above.
  • KeyedList(keys, default=0): every key gets the same default value.
  • KeyedList(other_klist): shares the values list and copies the index.

Reading and writing:

  • Read with row['a'], row.get('a', default), 'a' in row or row.items(). A list of keys, as in row[['a', 'b']], returns a list of values and skips keys that are missing.
  • Assigning to an existing key replaces the value in the list.
  • Assigning to a new key adds the key, and adds the value to the end of the list. If the list is a row of a Daf, that row is now longer than the others.
  • Deleting a key removes its value from the list.
  • A KeyedList that shares an index copies it before it adds a key. So adding a key to one row does not give that key to the other rows.

Speed:

Looping over a table as KeyedLists can be faster than looping over dicts, even if you never assign to a row. All the rows share one index, so no row builds its own. The gain grows with the number of columns. In a test with 50,000 rows of 400 columns, reading one field in a loop took 0.047 s with KeyedLists and 0.583 s with dicts. With 5 columns the two were about even.

Because a KeyedList points into the table, assigning to it changes the table. If you need a copy, use to_dict(), or loop with iter_dict() on the Daf.

Examples:

Make a KeyedList over a list of values, one key for each:

>>> values = ['Ana Lopez', 'Denver', 34]
>>> klist = KeyedList(['name', 'city', 'age'], values)

Read a value by its key, and set one. The change goes into the list itself:

>>> klist['city']
'Denver'
>>> klist['city'] = 'Boulder'
>>> values
['Ana Lopez', 'Boulder', 34]

Make a dict of it, and read a key that is not there with a default:

>>> klist.to_dict()
{'name': 'Ana Lopez', 'city': 'Boulder', 'age': 34}
>>> klist.get('email', 'none')
'none'

A row of a Daf is a KeyedList that points at the row in the table:

>>> from daffodil.daf import Daf
>>> daf = Daf(cols=['name', 'age'], lol=[['Ana Lopez', 34], ['Ben Okafor', 52]])
>>> daf

|    name    | age |
| ---------: | --: |
|  Ana Lopez |  34 |
| Ben Okafor |  52 |

%% daf rows=2; cols=2; keyfield=''; name=''

>>> for row in daf.iter_klist():
...     row['age'] = 0
>>> daf

|    name    | age |
| ---------: | --: |
|  Ana Lopez |   0 |
| Ben Okafor |   0 |

%% daf rows=2; cols=2; keyfield=''; name=''

__getitem__

__getitem__(key: List[K]) -> List[V]
__getitem__(key: K) -> V
__getitem__(key)

Get the value for a key, or a list of values for a list of keys.

Parameters:

Name Type Description Default
key K | List[K]

A key, or a list of keys.

required

Returns:

Type Description
V | List[V]

The value. For a list of keys, a list of values in that order. A key of the list that is

V | List[V]

missing is skipped, so the list can be shorter.

Raises:

Type Description
KeyError

A single key is not found.

ValueError

The key is not a list and cannot be hashed.

Examples:

Make a KeyedList of a person:

>>> klist = KeyedList(['name', 'city', 'age'], ['Ana Lopez', 'Denver', 34])

Read one value by key, and several by a list of keys. A key in the list that is not there is left out:

>>> klist['city']
'Denver'
>>> klist[['age', 'name']]
[34, 'Ana Lopez']
>>> klist[['name', 'email']]
['Ana Lopez']

__setitem__

__setitem__(key, value)

Set the value for a key, as row[key] = value.

A key that exists gets the new value in the list that this KeyedList points at. If that list is a row of a Daf, the Daf changes. A key that is new is added at the end of the keys, and its value at the end of the list, so a row of a Daf is then longer than the others. The index is copied before it gets a new key, so other KeyedLists that shared it do not get the key.

Parameters:

Name Type Description Default
key K

The key.

required
value V

The value.

required

Examples:

Make a KeyedList over a list of values:

>>> row = ['Ana Lopez', 34]
>>> klist = KeyedList(['name', 'age'], row)

Set a value by key, which changes the list. A new key adds a value at the end:

>>> klist['age'] = 35
>>> klist['city'] = 'Denver'
>>> row
['Ana Lopez', 35, 'Denver']
>>> list(klist)
['name', 'age', 'city']

__delitem__

__delitem__(key)

Delete a key and its value, as del row[key].

The value is removed from the list that this KeyedList points at, and the later values move down. If that list is a row of a Daf, the row is then shorter than the others. The index is rebuilt, and this KeyedList no longer shares it.

Parameters:

Name Type Description Default
key K

The key to delete.

required

Raises:

Type Description
KeyError

The key is not found.

Examples:

Make a KeyedList over a list of values:

>>> row = ['Ana Lopez', 'Denver', 34]
>>> klist = KeyedList(['name', 'city', 'age'], row)

Delete a key and its value, from the list too:

>>> del klist['city']
>>> row, list(klist)
(['Ana Lopez', 34], ['name', 'age'])

__len__

__len__()

Get the number of values.

Returns:

Type Description
int

The number of values in the list that this KeyedList points at.

Examples:

Count the keys:

>>> len(KeyedList(['name', 'age'], ['Ana Lopez', 34]))
2

__iter__

__iter__()

Loop over the keys, as a dict does.

Returns:

Type Description
Iterator[K]

An iterator of the keys, in the order of their values.

Examples:

Loop over the keys:

>>> list(KeyedList(['name', 'age'], ['Ana Lopez', 34]))
['name', 'age']

__contains__

__contains__(key)

Test whether a key is one of the keys, as key in row.

Parameters:

Name Type Description Default
key object

The key to look for.

required

Returns:

Type Description
bool

True if the key is found.

Examples:

Ask whether a key is there:

>>> 'name' in KeyedList(['name', 'age'], ['Ana Lopez', 34])
True
>>> 'email' in KeyedList(['name', 'age'], ['Ana Lopez', 34])
False

keys

keys()

Get the keys, in the order of their values.

This is a keys view of the index itself. When the index is shared with other KeyedLists, as it is for the rows of a Daf, it is not a copy. For a list of the keys, use list(row.keys()).

Returns:

Type Description
KeysView[K]

The keys.

Examples:

Read the keys, as a view:

>>> KeyedList(['name', 'age'], ['Ana Lopez', 34]).keys()
dict_keys(['name', 'age'])

set_values

set_values(new_values)

Point this KeyedList at a different list of values.

This replaces the list that the KeyedList adopted. It does not write into the old list. If the old list was a row of a Daf, the row is not changed, and this KeyedList stops being a view of it. The new list is adopted, not copied. To change the values in the old list, assign to the keys.

Parameters:

Name Type Description Default
new_values List[V]

The new list of values, one for each key.

required

Raises:

Type Description
TypeError

new_values is not a list. A tuple is not accepted.

ValueError

The list does not have one value for each key.

Examples:

Make a KeyedList over a list of values:

>>> row = ['Ana Lopez', 34]
>>> klist = KeyedList(['name', 'age'], row)

Replace all the values at once. The list given becomes the values:

>>> klist.set_values(['Ben Okafor', 52])
>>> klist.values(), row
(['Ben Okafor', 52], ['Ana Lopez', 34])

A list of the wrong length raises:

>>> klist.set_values(['Chen Wu'])
Traceback (most recent call last):
    ...
ValueError: values length must match keys

values

values(astype: None = None) -> List[V]
values(astype: Callable | str | type) -> List[Any]
values(astype=None)

Get the values as a list.

With no astype, or with list, this is the list that the KeyedList adopted, not a copy. If it is a row of a Daf, changing it changes the Daf. With any other astype it is a new list, and the original is not changed. An empty cell, which is NULL in daffodil, is not converted. It stays as the empty string.

Parameters:

Name Type Description Default
astype Callable | str | type | None

How to convert each value. A type such as int, a function, or one of the names 'int', 'str', 'float' and 'bool'. None does not convert.

None

Returns:

Type Description
List[Any]

The values.

Raises:

Type Description
ValueError

astype is a name that is not supported, or a value cannot be converted by int or float. Another converter raises its own error.

Examples:

Make a KeyedList of values read as text:

>>> klist = KeyedList(['age', 'visits'], ['34', '7'])

Read the values, as they are or converted to a type:

>>> klist.values()
['34', '7']
>>> klist.values(int)
[34, 7]
>>> klist.values('float')
[34.0, 7.0]
>>> KeyedList(['age', 'visits'], ['34', '']).values(int)
[34, '']
>>> klist.values() is klist.values()
True
>>> klist.values(int) is klist.values(int)
False
>>> klist.values('date')
Traceback (most recent call last):
    ...
ValueError: astype not supported: date

items

items()

Loop over the (key, value) pairs, as dict.items() does.

This is an iterator, not a view. It can be used once. To keep the pairs, use list(row.items()).

Returns:

Type Description
Iterator[Tuple[K, V]]

An iterator of (key, value) tuples.

Examples:

Read the keys and values as pairs. Each call gives a new iterator:

>>> list(KeyedList(['name', 'age'], ['Ana Lopez', 34]).items())
[('name', 'Ana Lopez'), ('age', 34)]
>>> pairs = KeyedList(['name'], ['Ana Lopez']).items()
>>> list(pairs), list(pairs)
([('name', 'Ana Lopez')], [])

get

get(key, default=None)

Get the value for a key, or a default if the key is not found.

Parameters:

Name Type Description Default
key K

The key.

required
default Any

What to return if the key is not found.

None

Returns:

Type Description
Any

The value, or default.

Raises:

Type Description
TypeError

The key cannot be hashed, such as a list. Unlike row[...], a list of keys is not accepted here.

Examples:

Read a value by key, with a default for a key that is not there:

>>> klist = KeyedList(['age'], [34])
>>> klist.get('age'), klist.get('email'), klist.get('email', 'none')
(34, None, 'none')

update

update(other)

Set many keys from a dict or from another KeyedList.

Each key of other is assigned as in row[key] = value. A key that exists gets the new value in the list. A key that is new is added at the end of the keys and of the list. If the list is a row of a Daf, that row is then longer than the others, so use update() only with keys that exist. other is not changed.

Parameters:

Name Type Description Default
other KeyedList | Dict[Any, Any]

A dict or a KeyedList.

required

Examples:

Make a KeyedList of a person:

>>> klist = KeyedList(['name', 'age'], ['Ana Lopez', 34])

Set several values from a dict. A new key adds a value:

>>> klist.update({'age': 35, 'city': 'Denver'})
>>> klist.to_dict()
{'name': 'Ana Lopez', 'age': 35, 'city': 'Denver'}

to_dict

to_dict()

Make a dict of the keys and values.

The dict is independent of this KeyedList. Later writes to the row do not change it, and changing it does not change the row. The values are not copied deeply, so a list or dict held in a cell is the same object in both.

Returns:

Type Description
Dict[K, V]

A new dict.

Examples:

Make a KeyedList of a person:

>>> klist = KeyedList(['name', 'age'], ['Ana Lopez', 34])

Make a dict of it. The dict is a copy, so a later change to the KeyedList does not reach it:

>>> as_dict = klist.to_dict()
>>> klist['name'] = 'Ana L. Lopez'
>>> as_dict
{'name': 'Ana Lopez', 'age': 34}

__repr__

__repr__()

Show the keys and values as a dict.

Returns:

Type Description
str

The text of the dict.

Examples:

Echo a KeyedList at the prompt to see its keys and values:

>>> KeyedList(['name', 'age'], ['Ana Lopez', 34])
{'name': 'Ana Lopez', 'age': 34}

__bool__

__bool__()

return true if there is something in the values list.

to_json

to_json()

Make a JSON string that holds the keys and the values.

The text has the marker __KeyedList__, the keys with their positions under hd, and the values. Every value must be one that json can write. JSON keys are text, so a key that is not a string, such as an int, comes back from from_json() as a string.

Returns:

Type Description
str

The JSON text.

Raises:

Type Description
TypeError

A value cannot be written as JSON.

Examples:

Make JSON text of a KeyedList:

>>> KeyedList(['age', 'name'], [34, 'Ana Lopez']).to_json()
'{"__KeyedList__": true, "hd": {"age": 0, "name": 1}, "values": [34, "Ana Lopez"]}'

from_json classmethod

from_json(json_str)

Make a KeyedList from the text that to_json() writes.

Parameters:

Name Type Description Default
json_str str

The JSON text.

required

Returns:

Type Description
KeyedList[Any, Any]

The new KeyedList. It has its own list of values.

Raises:

Type Description
ValueError

The text is not JSON, or the JSON does not have the __KeyedList__ marker.

Examples:

Make a KeyedList, write it as JSON, and read it back:

>>> klist = KeyedList(['age', 'name'], [34, 'Ana Lopez'])
>>> KeyedList.from_json(klist.to_json()).to_dict()
{'age': 34, 'name': 'Ana Lopez'}

The text must be what to_json() writes:

>>> KeyedList.from_json('{"age": 34}')
Traceback (most recent call last):
    ...
ValueError: Invalid JSON string for KeyedList