Skip to content

Merging Dictionaries

Add key Source: adopted from here

Introduction

One common operation on a dictionary is to add an new key to an existing dictionary. This operation looks quite easy and straightforward at first sight, but there is a trap to fall into.

Question

Suppose you have a dictionary d defined as follows:

q) d:`firstName`lastName!`Tom`Jerry

How to add a new key age with value 37 to this dictionary? After adding the new key, the updated dictionary should look like:

q) d
firstName| Tom
lastName | Jerry
age      | 37

Answer

The immediate solution that comes to many people's mind is to add the new key age is:

q) d[`age]:37

Unfortunately, a type error is thrown when doing that:

q) d[`age]:37
'type
  [0]  d[`age]:37
              ^

The type error occurs because:

  • The existing dictionary d is uniform, and
  • The value type of new item age is different from the value type of the existing items in the dictionary

Let's look at two different cases.

Mixed Value Type

A new key can be simply added by assigning the value to the new key when the existing dictionary's values are of mixed types. For example, the value of dictionary d2 has types of symbol and long, i.e., (`Tom;`Jerry;10583) is of mixed type.

q) d2:`firstName`lastName`zip!(`Tom;`Jerry;10583)
q) d2
firstName| `Tom
lastName | `Jerry
zipcode  | 10583

q) d2[`age]:37 / add a new item
q) d2
firstName| `Tom
lastName | `Jerry
zipcode  | 10583
age      | 37

Uniform Value Type

  • The new value has the same type as the existing dictionary's value
q) d3:`firstName`lastName!`Tom`Jerry
q) d3[`state]:`NY
q) d3
firstName| Tom
lastName | Jerry
state    | NY
  • The new value's type is different from the type of the existing dictionary's value. In this case, we can create a second dictionary using the new key/value and then merge this dictionary with the existing dictionary. For example,
q) d4:`firstName`lastName!`Tom`Jerry
q) d4
firstName| Tom
lastName | Jerry

q) d4,(enlist `age)!(enlist 37)
firstName| `Tom
lastName | `Jerry
age      | 37

The right side of the join operator (,) above is a singleton dictionary. Note that both the key and the value of a dictionary are required to be lists, you must enlist atomic value to create a singleton dictionary.

A generic approach

The q-sql update template can be used to update a dictionary:

update age:37,zipcode:10583,address:"231 Park Ave" from d

This approach is very generic and works irrespective the value types of the existing dictionary.

Summary

The robust approaches to insert a new item into an dictionary are:

  1. first create a new dictionary using the new item and merge this new dictionary with the existing dictionary using the join operator.
  2. use q-sql the update template to add new items to a dictionary or update the value of an existing item.