Reputation: 638
I want to get any key/value pair from associative array and remove it. In python it's:
key, value = assoc.popitem()
In D I do:
auto key = assoc.byKey.front;
auto value = assoc[key];
assoc.remove(key);
Is there better way to do this? Is it possible to use byKeyValue() outside foreach?
DMD 2.067.1
Upvotes: 5
Views: 201
Reputation: 25605
Before even thinking about it, I'd point out that you could 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);
}
Generally, I like to encourage people not to be afraid of writing 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 that! With the uniform function call syntax, you can easily even write extension methods for built in types, like I did here, and use it as if it has always been there.
Upvotes: 4
Reputation: 25187
Is it possible to use byKeyValue() outside 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 better way to do this?
I don't think D has a library function equivalent for popitem
.
Upvotes: 4