Oktatás * Programozás 1 * Szkriptnyelvek Teaching * Programming 1 (BI) Félévek Linkek * kalendárium |
DLang /
Create a dictionary; read/writeDictionaries in D are unordered collections.
Notice that when you specify the type of a dictionary, then the order is a bit strange: Passint a dictionary to a function
It behaves just like in Python. Remove an element; remove all elements
In Python, when you want to remove an element by using a non-existing key, you get an error. In D, the function The
|
(4) in | |
def main(): d = {} d[1] = "one" d[2] = "two" d[3] = "three" print(d) # {1: 'one', 2: 'two', 3: 'three'} if 2 in d: print("2 was found") # will be printed if 9 not in d: print("9 was not found") # will be printed |
import std.stdio; void main() { string[int] d; d[1] = "one"; d[2] = "two"; d[3] = "three"; writeln(d); // [3:"three", 2:"two", 1:"one"] if (2 in d) { writeln("2 was found"); // will be printed } if (9 !in d) { writeln("9 was not found"); // will be printed } } |
get()
function (5) get()
| |
def main(): d = {} d[1] = "one" d[2] = "two" d[3] = "three" print(d) # {1: 'one', 2: 'two', 3: 'three'} # print(d[9]) # KeyError, no such key print(d.get(9)) # None print(d.get(9, "not found")) # "not found" |
import std.stdio; void main() { string[int] d; d[1] = "one"; d[2] = "two"; d[3] = "three"; writeln(d); // [3:"three", 2:"two", 1:"one"] // writeln(d[9]); // error, no such key // writeln(d.get(9)); // error, no such function // a default value MUST be provided writeln(d.get(9, "not found")); // "not found" } |
(6) length, keys, values | |
def main(): d = {} d[1] = "one" d[2] = "two" d[3] = "three" print(d) # {1: 'one', 2: 'two', 3: 'three'} # 1 print(len(d)) # 3, number of key/value pairs # 2 key_list = list(d.keys()) print(key_list) # [1, 2, 3] # 3 value_list = list(d.values()) print(value_list) # ['one', 'two', 'three'] # 4 for k in d.keys(): # loop over an iterator print(k) # 5 for k in d: # same as before (loop over the keys) print(k) # 6 for v in d.values(): # loop over an iterator print(v) # 7 for k, v in d.items(): # loop over an iterator print(k, "->", v) |
import std.stdio; void main() { string[int] d; d[1] = "one"; d[2] = "two"; d[3] = "three"; writeln(d); // [3:"three", 2:"two", 1:"one"] // 1 writeln(d.length); // 3, number of key/value pairs // 2 writeln(d.keys()); // [3, 2, 1], as list // 3 writeln(d.values()); // ["three", "two", "one"], as list // 4; no list is created; we loop over a range foreach (k; d.byKey) { writeln(k); } // 5; !!! it iterates over the VALUES !!! foreach (v; d) { writeln(v); } // 6; no list is created; we loop over a range foreach (v; d.byValue) { writeln(v); } // 7a foreach (k, v; d) { writeln(k, " -> ", v); } // 7b; unpacking doesn't work here foreach (pair; d.byKeyValue) { writeln(pair.key, " -> ", pair.value); } } |
The by*()
functions return a range, not a list.
Blogjaim, hobbi projektjeim
* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák
[ edit ]