Hacker News new | ask | show | jobs
by z9znz 1440 days ago
> I’ve also never seen any code that need to get the first item out of a dict, what does that even mean?

You have a dict which contains a collection of similar values indexed by one value (which is the key). These may be records of people, and the key could be their phone number. Or it's documents indexed by some id, and the id is the key. Or orders keyed on order_id.

If you need to make a decision about processing based on some characteristic of the first item, you're not going to loop over the collection; you just need to know the key or possibly some element within the value of the first item in that dict.

Lists, dicts, tuples, sets, etc. are all collections. Why should collections not have as consistent features (and behaviors) as possible? Every collection has a first item. Maybe for unordered collections it doesn't make sense, but only set is unordered here.

It's nice to be able to go from general to specific, and to stay as high up that ladder as possible. And when designing systems that push complexity to the edges, the fewer ways of doing the same conceptual things, the better.

Python provides pop() for lists and dicts, and those both operate on positional data within their respective structures. Python could add first(), nth(), take(), and other nice conveniences to their collections. The low level implementation could be optimized, but the developer would have the benefit of common concepts.

Consistency matters a lot, because it means once we learn a concept or pattern we can apply that pattern generally without having to make a lot of changes for special cases.

For example:

h = {a: 1, b: 2}

h.map { |k,v| v * 10 } => [10, 20]

You could probably have guessed what that did even if you didn't know Ruby.

a = [1, 2]

a.map { |x| x * 10 } => [10, 20]

The only difference here was that we knew that each element was a single value rather than a key value pair (which we destructured into k and v in the previous example).

But let's do the same in Python.

d = {'a': 1, 'b': 2}

[v * 10 for v in list(d.values())] => [10, 20]

l = [1, 2]

[v * 10 for v in l] => [10, 20]

Or of course you could just do this:

list(map(lambda kv : (kv[1] * 10), d.items())) => [10, 20]