4 ms·
I've been in Python/Django for about a year now and I really miss Ruby's hash vs the dict. `.dig(:key, :key, :etc)` is so nice to find deeply nested data witho
by irjustin 3y ago
I've been in Python/Django for about a year now and I really miss Ruby's hash vs the dict.
`.dig(:key, :key, :etc)` is so nice to find deeply nested data without blowing up.
One thing I don't miss is knowing whether a hash's keys are strings vs symbols. While it's easily solvable, I've definitely lost time only to smack myself that I need to use a str but was always feeding a sym and swore that this should be a sym based hash.
- code_biologist 3y agoI don't know ruby and if it's the same, but if you're not using a library like funcy or toolz for a nested get helper, you can do `dict.get('key', {}).get('key2', {}).get('key3')`. Not the prettiest, but can do in a pinch.
- irjustin 3y agoThanks! i didn't know about these and will check them out for sure. Tired of `if key in hash:` nested layers.
- nicolaslem 3y agoIn my opinion, a better alternative to nested `if key in hash`: try: value = data["foo"]["bar"]["baz"] except KeyError: value = None
- irjustin 3y agoI know it's been almost a year but I still haven't accepted this pattern. Using errors as general flow control makes me uncomfortable. It shouldn't be an error or exception except in.... Actual problems.