Is there a method like python popitem for associative arrays in dlang?

I want to get a key / value pair from an associative array and delete it. In python, this is:

key, value = assoc.popitem() 

In D, I do:

 auto key = assoc.byKey.front; auto value = assoc[key]; assoc.remove(key); 

Is there a better way to do this? Is it possible to use byKeyValue () outside of foreach?

DMD 2.067.1

+5
source share
2 answers

Is it possible to use byKeyValue () outside of foreach?

Sure:

 import std.stdio; void main() { int[string] assoc = ["apples" : 2, "bananas" : 4]; while (!assoc.byKeyValue.empty) { auto pair = assoc.byKeyValue.front; assoc.remove(pair.key); writeln(pair.key, ": ", pair.value); } } 

Is there a better way to do this?

I don't think D has a library function equivalent to popitem .

+4
source

Before even thinking about this, I would point out that you can write a simple function:

 import std.typecons; Tuple!(K, V) popitem(K, V)(ref V[K] arr) { foreach(k, v; arr) { arr.remove(k); return tuple(k, v); } throw new Exception("empty!"); } void main() { int[string] cool; cool["ten"] = 10; cool["twenty"] = 20; import std.stdio; writeln(cool.popitem()); writeln(cool.popitem()); } 

Or using byKeyValue:

 auto popitem(K, V)(ref V[K] arr) { foreach(item; arr.byKeyValue()) { arr.remove(item.key); return item; } throw new Exception("empty!"); } void main() { int[string] cool; cool["ten"] = 10; cool["twenty"] = 20; import std.stdio; auto item = cool.popitem(); writeln(item.key, item.value); item = cool.popitem(); writeln(item.key, item.value); } 

In general, I like to encourage people not to be afraid to write their own functions. If you can express something with a few existing things, just write your own function, give it a name you like, and use it! With the syntax of uniform functions, you can easily even write extension methods for built-in types like I am here, and use it as if it were always there.

+4
source

All Articles