DEV Community

loading...

Filter a Dictionary in D

Jesse Phillips
Senior Quality Assurance (SDET) ¶ Avid hobby D programmer ¶ Telling people what to do because I am right.
・1 min read

This wasn't so much about filtering the content, but instead having a list of dictionaries and filtering to ones with specific data.

auto data = [["key": 5], ["key": 2]];

auto foo = data.filter!(x => x["key"] == 5);
Enter fullscreen mode Exit fullscreen mode

Well I showed this with my count example, it is one of the reasons I like D. I just keep with the same tools and there is similarities in how they all work. One of the challenges can be producing the ability to traverse, let me dive into this dictionary filtering.

import std.array;

auto dict = ["one" : 1
           , "two" : 2
           , "three" : 3];

dict.byPair
    .filter!(x => x[0] == "one")
    .assocArray;
Enter fullscreen mode Exit fullscreen mode

In this case I'm asking to traverse the dictionary by each key/value pair. After the filtering we build out a new dictionary.

As an aside, while I find consistency in these, I'm also aware D has inconsistency.

Discussion (0)