Search code examples
hashmaptclassociative-array

Duplicate keys in tcl associative array


I am using associative array/hash map to store some data. I want to keep duplicate entries that have same key but different values. Currently, the previous key is being overwritten by the last instance.

key: LVL values: vdd,vddr

key: LVL values: vddi,vdd


Solution

  • Multimaps are, in general, implemented as ordinary maps to lists of items. (There's a few other ways, algorithmically, but they're rare in practice except in a few degenerate cases.) In Tcl, you do this by appending to the list in the element on creation and using nested loops on read out:

    # With arrays
    foreach {key item} $thingsToPutIn {
        lappend map($key) $item
    }
    
    foreach {key items} [array get map] {
        foreach item $items {
            puts "$key => $item"
        }
    }
    
    # With dictionaries
    foreach {key item} $thingsToPutIn {
        dict lappend map $key $item
    }
    
    dict for {key items} $map {
        foreach item $items {
            puts "$key => $item"
        }
    }