Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tracking some ideas #347

Open
kurtbrose opened this issue Aug 24, 2023 · 4 comments
Open

tracking some ideas #347

kurtbrose opened this issue Aug 24, 2023 · 4 comments

Comments

@kurtbrose
Copy link
Contributor

These need gardening but I'll just put them here to keep track.

def get_any(dict, *keys, default=None):
    """Cascading get, for those times you do `dict.get(key1, dict.get(key2, ...))"""
    for key in keys:
        if key in dict:
            return dict[key]
    return default

But I had another take on get_any() here, so need to resolve that.
#266

Another one is a multi-partition, where predicates cascade:

future, current, past = partition(items, lambda item: item.start > now, lambda item: item.end > now)

(this could be an extension of iterutils.partition to accept any number of predicates instead of just one)

@kurtbrose
Copy link
Contributor Author

I've used this in 5 places now, I think there's definitely a handy primitive here, although I'm not sure if I got the name quite right:

def dict_zip(*dicts):
    for key in set().union(*dicts):
        yield tuple([key] + [d.get(key) for d in dicts])

@mahmoud
Copy link
Owner

mahmoud commented Sep 26, 2023

Looks like a full join to me. If using the zip name, I'd prefer zip_dicts over dict_zip.

In terms of a motivating example for docs, anything you can share about where the dicts are coming from / going to?

@Pandede
Copy link

Pandede commented Oct 3, 2023

May you provide some examples for your ideas?

@kurtbrose
Copy link
Contributor Author

a cousin of bucketize, but instead of [val] -> {key: val} it does {key: val} -> {key2: {key: val}}

def key_nest(dict_: dict[K, V], category: Callable[[K], K2]) -> dict[K2, dict[K, V]]:
    """Given a dict, return a dict-of-dicts split up by category(key) in the original dict"""
    categorized: dict[K2, dict[K, V]] = {}
    for key, val in dict_.items():
        category_key = category(key)
        categorized.setdefault(category_key, {})[key] = val
    return categorized

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants