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
A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take more memory because for each value there is also a key.
What is an associative array? Associative arrays are basically objects in JavaScript where indexes are replaced by user-defined keys. They do not have a length property like a normal array and cannot be traversed using a normal for loop.
In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an associative array is a function with finite domain.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With