Q语言 - 词典

词典是列表的扩展,为创建表提供了基础.在数学术语中,字典创建

"domain → 范围"

或一般(短)创建

"key → 值"

元素之间的关系.

字典是键值对的有序集合,大致相当于哈希表.字典是由域列表和范围列表之间的显式I/O关联通过位置对应定义的映射.创建字典使用"xkey"原语(!)

 
 ListOfDomain! ListOfRange

最基本的字典将简单列表映射到简单列表.

输入(I)输出(O)
`姓名`John
`年龄36
`性别"M"
重量60.3
q)d:`Name`Age`Sex`Weight!(`John;36;"M";60.3)   / Create a dictionary d

q)d

Name   | `John
Age    | 36
Sex    | "M"
Weight | 60.3

q)count d             / To get the number of rows in a dictionary.
4

q)key d               / The function key returns the domain
`Name`Age`Sex`Weight

q)value d             / The function value returns the range.

`John
36

"M"
60.3

q)cols d             / The function cols also returns the domain.
`Name`Age`Sex`Weight

Lookup

查找对应的字典输出值输入值被称为查找输入.

q)d[`Name]       / Accessing the value of domain `Name
`John

q)d[`Name`Sex]   / extended item-wise to a simple list of keys
`John
"M"

使用Verb查找

 
q)d1:`one`two`three! 9 18 27 
q)d1 [`2] 
 18 
q)d1 @`2 
 18

字典操作

Amend and Upsert

与列表一样,字典的项目可以通过索引修改赋值.

d:`Name`Age`Sex`Weight! (`John;36;"M";60.3)
                                  / A dictionary d
                                  
q)d[`Age]:35                      / Assigning new value to key Age

q)d 
                              / New value assigned to key Age in d
Name   | `John
Age    | 35
Sex    | "M"
Weight | 60.3

可以通过索引分配扩展字典.

q)d[`Height]:"182 Ft"

q)d

Name   | `John
Age    | 35
Sex    | "M"
Weight | 60.3
Height | "182 Ft"

使用查找反向查找(?)

查找(?)运算符用于执行通过将一系列元素映射到其域元素来进行反向查找.

q)d2:`x`y`z!99 88 77

q)d2?77
`z

如果列表的元素不是唯一的, find 返回从域列表映射到它的第一个项目.

删除条目

要从字典中删除条目,使用删除(_)功能. (_)的左操作数是字典,右操作数是键值.

q)d2:`x`y`z!99 88 77

q)d2 _`z

x| 99
y| 88

如果第一个操作数是变量,则_的左边需要空格.

q)`x`y _ d2           / Deleting multiple entries

z| 77

列词典

列词典是创建表格的基础知识.考虑以下示例 :

q)scores: `name`id!(`John`Jenny`Jonathan;9 18 27)
                              / Dictionary scores
                              
q)scores[`name]               / The values for the name column are
`John`Jenny`Jonathan

q)scores.name                 / Retrieving the values for a column in a
                              / column dictionary using dot notation.
`John`Jenny`Jonathan

q)scores[`name][1]            / Values in row 1 of the name column
`Jenny

q)scores[`id][2]              / Values in row 2 of the id column is
27

翻译字典

翻转列字典的净效果只是颠倒了索引的顺序.这在逻辑上等同于转置行和列.

翻译列字典

通过应用一元翻转获得字典的转置运营商.看看以下示例 :

q)scores

name  | John Jenny Jonathan
id    | 9   18   27

q)flip scores

  name     id
---------------
  John     9
  Jenny    18
 Jonathan  27

翻转翻译列字典

如果你转置一个字典两次,你得到原始字典,

q)scores ~ flip flip scores
1b