1 | #### "in" and "not in" on Dicts
|
2 |
|
3 | var d = {spam: 42, eggs: []}
|
4 |
|
5 | var b = 'spam' in d
|
6 | echo $b
|
7 |
|
8 | var b = 'zz' in d
|
9 | echo $b
|
10 |
|
11 | var b = 'zz' not in d
|
12 | echo $b
|
13 |
|
14 | var L = [1, 2, 3]
|
15 | var b = 3 in L # not allowed!
|
16 |
|
17 | echo should not get here
|
18 |
|
19 | ## status: 3
|
20 | ## STDOUT:
|
21 | true
|
22 | false
|
23 | true
|
24 | ## END
|
25 |
|
26 | #### dict with 'bare word' keys
|
27 | var d0 = {}
|
28 | echo len=$[len(d0)]
|
29 | var d1 = {name: "hello"}
|
30 | echo len=$[len(d1)]
|
31 | var d2 = {name: "hello", other: 2}
|
32 | echo len=$[len(d2)]
|
33 | ## STDOUT:
|
34 | len=0
|
35 | len=1
|
36 | len=2
|
37 | ## END
|
38 |
|
39 | #### dict with expression keys
|
40 | var d1 = {['name']: "hello"}
|
41 | echo len=$[len(d1)]
|
42 | var v = d1['name']
|
43 | echo $v
|
44 |
|
45 | var key='k'
|
46 | var d2 = {["$key"]: "bar"}
|
47 | echo len=$[len(d2)]
|
48 | var v2 = d2['k']
|
49 | echo $v2
|
50 |
|
51 | ## STDOUT:
|
52 | len=1
|
53 | hello
|
54 | len=1
|
55 | bar
|
56 | ## END
|
57 |
|
58 |
|
59 | #### dict literal with implicit value
|
60 | var name = 'foo'
|
61 | var d1 = {name}
|
62 | echo len=$[len(d1)]
|
63 | var v1 = d1['name']
|
64 | echo $v1
|
65 |
|
66 | var d2 = {name, other: 'val'}
|
67 | echo len=$[len(d2)]
|
68 | var v2 = d2['name']
|
69 | echo $v2
|
70 |
|
71 | ## STDOUT:
|
72 | len=1
|
73 | foo
|
74 | len=2
|
75 | foo
|
76 | ## END
|
77 |
|
78 | #### Dict literal with string keys
|
79 | var d = {'sq': 123}
|
80 | var v = d['sq']
|
81 | echo $v
|
82 |
|
83 | var x = "q"
|
84 | var d2 = {"d$x": 456}
|
85 | var v2 = d2["dq"]
|
86 | echo $v2
|
87 | ## STDOUT:
|
88 | 123
|
89 | 456
|
90 | ## END
|
91 |
|
92 |
|
93 | #### keys(d), values(d), get(d, key)
|
94 |
|
95 | var d = {a: 42, b: 99}
|
96 |
|
97 | pp test_ (keys(d))
|
98 | pp test_ (values(d))
|
99 |
|
100 | pp test_ (get(d, 'a', 'default'))
|
101 | pp test_ (get(d, 'key', 'default'))
|
102 |
|
103 | ## STDOUT:
|
104 | (List) ["a","b"]
|
105 | (List) [42,99]
|
106 | (Int) 42
|
107 | (Str) "default"
|
108 | ## END
|
109 |
|
110 | #### get() has default null
|
111 |
|
112 | var d = {a: 42}
|
113 |
|
114 | pp test_ (get(d, 'b'))
|
115 |
|
116 | ## STDOUT:
|
117 | (Null) null
|
118 | ## END
|
119 |
|
120 |
|