#๐Ÿ”’ Is a defaultdict or dataclass useful here?

10 messages ยท Page 1 of 1 (latest)

rain forge
#

I'm reading up on dataclasses as an alternative to dictionaries with the @dataclass(frozen=True) to make the entries immutable but I don't see how it makes a significant improvement to how the id is retrieved. One thing I would like to improve is maybe how the ids_needed is retrieved and that the user_input is part of the keys of ID_REFERENCE


def do_something(id: str) -> None:
  pass

# Default is id i.e. c and e
# as a dict in a config file, easy to reference
ID_REFERENCE: dict[str, str] = {
  "a": "a_id",
  "b": "b_id",
  "c": "id",
  "d": "d_id",
  "e": "id"
}

# elements are from external service and must be one of the keys in ID_REFERENCE
user_input: list[str] = ["a", "c", "d"]

created_objects: list[str] = ["c", "d", "f", "g"]

# Retrieve objs in ID_REFERENCE and user_input and created_objects
ids_needed: set[str] = set(list(ID_REFERENCE.keys())) & \
              set(user_input) & \
              set(created_objects)

for obj in ids_needed:
  do_something(ID_REFERENCE.get(obj))

glad oakBOT
#

@rain forge

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

versed nymph
rain forge
midnight lark
#

that would leave "dataclasses are an alternative to dicts" which is also not true

#

dataclasses are an easy way to make classes

#

dicts map values to other values

rough skiff
#

In particular, classes tend to get things ad .something vs dicts which are ["something"].
So with classes, usually there is a fixed set of attributes whose names and meanings you know.
With a dict, you often have an arbitrary collection of keys and their values, and they don't really have "different" meanings except in as far as the values are different.

glad oakBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.