Using the SetDefault Method in Python for Handling Lists Within Dicts

preview_player
Показать описание
This video explains the setdefault dictionary method for adding list items to a dictionary when keys are unknown.

WORK WITH ME👇🏼

✅ Need help with your project? Schedule a call with me at:

Рекомендации по теме
Комментарии
Автор

Didn't know it existed either :-) I always used `from collections import defaultdict` and then instead of `animal_dict = {}`, I've used `animal_dict = defaultdict(list)`.
My test of omparing speed with `timeit` module (50 x 10 000 000) with 4 dictionary items: IF Conditional ... 0.088, Defaultdict ... 0.090, Setdefault ... 0.089
Readability counts, I wouldn't write it like IF conditional just for the speed. Defaultdict or Setdefault are both good ways in my opinion, BUT as I found on the internets, SETDEFAULT sets its default per element when it is read. collections.DEFAULTDICT sets its default for the entire dict at creation time.
I would say it depends on the number of elements. Defaultdict would be nearly always faster.
One person on StackOverflow: One reason to use setdefault is when the default you assign is based on the key (or something) rather than a generic default for the entire dict.

songokussjcz
Автор

In the second example:
animal_dict = {}
for animal in animals:
if animal['type'] in animal_dict:

else:
animal_dict[animal['type']] = animal['breed']
print(animal_dict)
It raises an AttributeError: 'str' object has no attribute 'append' for me.
Can you, please, tell me why? I did exactly as you did... Or not?

msgrz
Автор

Is there any runtime advantage? Great info, didn't know this existed.

cviddy
Автор

collections.defauldict seems a much better solution tbh

Calg
Автор

зачем люди говорят на английском? Что за выдуманный язык? Легче просто делать видео на русском и не волноваться

Чифкиф-чд
welcome to shbcf.ru