Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2024/25/2
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Scala


[ edit | logout ]
[ sandbox | passwd ]

Create a dictionary; read/write

Dictionaries in D are unordered collections.

(1) create a dictionary; read/write
def main():
    # d: dict[int, str] = {}
    d = {}
    d[1] = "one"
    d[3] = "three"
    print(d)  # {1: 'one', 3: 'three'}

    d2 = {
        1: "one",
        3: "three"
    }
    print(d2)  # {1: 'one', 3: 'three'}

    # print a value
    print(d[1])  # one
import std.stdio;

void main()
{
    string[int] d;  // order: value[key]
    d[1] = "one";
    d[3] = "three";
    writeln(d); // [3:"three", 1:"one"]

    auto d2 = [
        1: "one",
        3: "three"
    ];
    writeln(d2); // [3:"three", 1:"one"]

    // print a value
    writeln(d[1]); // one
}
def main():
    d = {}
    d[1] = ["one", "egy"]
    d[2] = ["two", "kettő"]
    d[3] = ["three", "három"]
    print(d)
    """
    {1: ['one', 'egy'],
     2: ['two', 'kettő'],
     3: ['three', 'három']}
    """
import std.stdio;

void main()
{
    string[][int] d;
    d[1] = ["one", "egy"];
    d[2] = ["two", "kettő"];
    d[3] = ["three", "három"];
    writeln(d);
    /* [3:["three", "három"],
        2:["two", "kettő"],
        1:["one", "egy"]] */

}

Notice that when you specify the type of a dictionary, then the order is a bit strange: value_type[key_type]. Well, when you want to access a value, we use this syntax: writeln(d[1]);, i.e. we indicate the key between the square brackets.

Passint a dictionary to a function

(2) passing to a function
def modify(d: dict) -> None:
    d[2] = "two"

def main():
    d = {}
    d[1] = "one"
    d[3] = "three"
    print(d)  # {1: 'one', 3: 'three'}

    modify(d)

    print(d)  # {1: 'one', 3: 'three', 2: 'two'}
import std.stdio;

void modify(string[int] d)
{
    d[2] = "two";
}

void main()
{
    string[int] d;
    d[1] = "one";
    d[3] = "three";
    writeln(d); // [3:"three", 1:"one"]

    modify(d);

    writeln(d); // [3:"three", 2:"two", 1:"one"]
}

It behaves just like in Python. d is an object (a reference pointing on an object), and thus the object is passed by reference. If you change the dictionary in a function, the caller will see the changes.

Remove an element; remove all elements

(3) remove element(s)
def main():
    d = {}
    d[1] = "one"
    d[2] = "two"
    d[3] = "three"
    print(d)  # {1: 'one', 2: 'two', 3: 'three'}

    del d[2]
    print(d)  # {1: 'one', 3: 'three'}

    # del d[2]  # KeyError exception, no such key

    d.clear()
    print(d)  # {}
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"]

    d.remove(2); // returns true, key found
    writeln(d); // [3:"three", 1:"one"]

    d.remove(2); // returns false, no such key
    writeln(d); // [3:"three", 1:"one"]

    d.clear();
    writeln(d); // []
}

In Python, when you want to remove an element by using a non-existing key, you get an error. In D, the function remove() returns false in this case.

The in operator

(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
    }
}

The 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"
}

Length, keys, values

(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.

Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2025 July 01, 17:16