Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Julia Dictionaries and Sets

Julia Dictionaries and Sets

BesidesarraysandTuple, Julia also provides two commonly used collections: dictionaries (Dict) and Set (unordered collection).


Dictionaries

A dictionary is a mutable container model that can store objects of any type.

Each key-value pair of a dictionary is separated by =>, the pairs are separated from each other by the comma , symbol, and the whole dictionary is enclosed in curly braces {}.

Creating a dictionary

The syntax for creating a dictionary is as follows:

Dict("key1" => value1, "key2" => value2, ..., "keyn" => valuen)

The following example creates a simple dictionary where key A maps to value 1 and key B maps to value 2:

Example

julia

D =

Dict

(

"A"

=

1

,

"B"

=

2

)

Dict

{

String

,

Int64

}

with

2

entries:

 

"B"

=

2

 

"A"

=

1

Julia automatically infers the types of keys and values, as in the above example Dict{String, Int64}. The types can also be specified explicitly:

Example

julia

D =

Dict

{

String

,

Float64

}

(

"A"

=

1

,

"B"

=

2

)

Dict

{

String

,

Float64

}

with

2

entries:

 

"B"

=

2.0

 

"A"

=

1.0

Use a comprehension to create a dictionary:

Example

julia

first_dict =

Dict

(

string

(

x

)

=

sind

(

x

)

for

x =

0

:

5

:

90

)

Dict

{

String

,

Float64

}

with

19

entries:

 

"85"

=

0.996195

 

"20"

=

0.34202

  ...

Accessing a dictionary

Use square brackets with a key to access the corresponding value:

Example

julia

D =

Dict

(

"A"

=

1

,

"B"

=

2

)

;

julia

D

[

"A"

]

1

Accessing a nonexistent key throws KeyError

julia

D

[

"X"

]

ERROR: KeyError: key

"X"

not found

If you want to return a default value for a nonexistent key without raising an error, use the get() function; get!() also writes the default value back into the dictionary:

Example

julia

get

(

D,

"X"

,

0

)

     

When the key does not exist, return the default value 0

0

julia

get

(

D,

"A"

,

0

)

     

When the key exists, return the actual value

1

julia

get

!

(

D,

"C"

,

3

)

   

C does not exist; write and return the default value

3

Adding and modifying

Keys in a dictionary are unique; if we assign a value to an already existing key, no new key is created and the value of the existing key is modified:

Example

julia

D

[

"C"

]

=

3

     

Add a new key/value pair

3

julia

D

[

"A"

]

=

100

   

Modify the value of an existing key

100

julia

D

Dict

{

String

,

Int64

}

with

3

entries:

 

"B"

=

2

 

"A"

=

100

 

"C"

=

3

Delete a key-value pair

We can use the delete!() function to remove a key from an existing dictionary:

Example

julia

delete

!

(

D,

"C"

)

Dict

{

String

,

Int64

}

with

2

entries:

 

"B"

=

2

 

"A"

=

100

pop!(D, key) removes the key-value pair and returns the removed value.

Querying keys

We can use the haskey() function to check whether the dictionary contains the specified key:

Example

julia

haskey

(

D,

"A"

)

true

julia

haskey

(

D,

"Z"

)

false

in checks the complete key-value pair

julia

in

(

(

"A"

=

100

)

, D

)

true

julia

keys

(

D

)

   

Get all keys

KeySet

for

a

Dict

{

String

,

Int64

}

with

2

entries.

Keys

:

 

"B"

 

"A"

Querying values and iteration

We can use values() to view all values of the dictionary and iterate over key-value pairs by treating the dictionary as an iterable object:

Example

julia

values

(

D

)

ValueIterator

for

a

Dict

{

String

,

Int64

}

with

2

entries.

Values

:

 

2

 

100

julia

for

kv

in

D

           

println

(

kv

)

       

end

"B"

=

2

"A"

=

100

Keys and values can also be destructured at the same time

julia

for

(

k, v

)

in

D

           

println

(

"The value of key $k is $v"

)

       

end

The value of key B is

2

The value of key A is

100

Merging dictionaries

merge() returns a new merged dictionary; on key conflicts, the later dictionary overrides the earlier value, while merge!() merges in place into the first dictionary:

Example

julia

d1 =

Dict

(

"a"

=

1

,

"b"

=

2

)

;

julia

d2 =

Dict

(

"b"

=

3

,

"c"

=

4

)

;

julia

merge

(

d1, d2

)

   

The value of b is overridden by d2

Dict

{

String

,

Int64

}

with

3

entries:

 

"a"

=

1

 

"b"

=

3

 

"c"

=

4

mergewith lets you customize the merge rule for conflicts

julia

mergewith

(

)

(

d1, d2

)

   

Add on conflict

Dict

{

String

,

Int64

}

with

3

entries:

 

"a"

=

1

 

"b"

=

5

 

"c"

=

4

Sorting a dictionary

A dictionary itself is unordered, but we can sort the keys with the sort() function and then iterate:

Example

julia

runoob_dict =

Dict

(

"R"

=

100

,

"S"

=

220

,

"T"

=

350

,

"U"

=

400

,

"V"

=

575

,

"W"

=

670

)

;

julia

for

key

in

sort

(

collect

(

keys

(

runoob_dict

)

)

)

           

println

(

"$key => $(runoob_dict[key])"

)

       

end

R =

100

S =

220

T =

350

U =

400

V =

575

W =

670

If the dictionary needs to stay sorted at all times, you can use the SortedDict data type from the DataStructures package.

To use a third-party package you must install it first; enter the symbol ] in the REPL to enter pkg mode:

julia> ]               # 输入 ] 就进入 pkg 模式

The syntax for adding a package is add PackageName; below we add the DataStructures package:

(@v1.10) pkg> add DataStructures

For unregistered packages, you can specify a url directly:

pkg> add https://github.com/fredrikekre/ImportMacros.jl

Local package:

pkg> add 本地路径/包名.jl

Example

julia

import

DataStructures

julia

runoob_dict = DataStructures.

SortedDict

(

"S"

=

220

,

"T"

=

350

,

"U"

=

400

,

"V"

=

575

,

"W"

=

670

)

DataStructures.

SortedDict

{

String

,

Int64

, Base.

Order

.

ForwardOrdering

}

with

5

entries:

 

"S"

=

220

 

"T"

=

350

  ...

julia

runoob_dict

[

"R"

]

=

100

100

julia

runoob_dict    

Keys always stay sorted

DataStructures.

SortedDict

{

String

,

Int64

, Base.

Order

.

ForwardOrdering

}

with

6

entries:

 

"R"

=

100

 

"S"

=

220

  ...


Set

A Julia Set (collection) is a data set with no duplicate objects; all elements are unique.

The following are the differences between Set and other types of collections:

Creating a Set collection

With the Set constructor, we can create collections like the following:

Example

julia

var_site =

Set

(

)

Set

{

Any

}

(

)

julia

num_primes =

Set

{

Int64

}

(

)

Set

{

Int64

}

(

)

julia

var_site =

Set

{

String

}

(

[

"Google"

,

"Runoob"

,

"Taobao"

]

)

Set

{

String

}

with

3

elements:

 

"Google"

 

"Taobao"

 

"Runoob"

We can use the push!() function to add elements to a set:

Example

julia

push

!

(

var_site,

"Wiki"

)

Set

{

String

}

with

4

elements:

 

"Google"

 

"Wiki"

 

"Taobao"

 

"Runoob"

Adding a duplicate element has no effect

julia

push

!

(

var_site,

"Runoob"

)

Set

{

String

}

with

4

elements:

 

"Google"

 

"Wiki"

 

"Taobao"

 

"Runoob"

We can use the in() function to check whether an element exists in a set:

Example

julia

in

(

"Runoob"

, var_site

)

true

julia

"Zhihu"

in

var_site    

Infix notation of in

false

Set Operations

Union, intersection, and set difference are some common operations we can perform on sets; the functions corresponding to these operations are union(), intersect() and setdiff():

Example

julia

A =

Set

{

String

}

(

[

"red"

,

"green"

,

"blue"

,

"black"

]

)

;

julia

B =

Set

(

[

"red"

,

"orange"

,

"yellow"

,

"green"

,

"blue"

,

"indigo"

,

"violet"

]

)

;

Union: the set formed by combining all elements of two sets:

Example

julia

union

(

A, B

)

Set

{

String

}

with

8

elements:

 

"indigo"

 

"green"

 

"black"

 

"yellow"

  ...

Intersection: the set of elements that belong to both A and B:

Example

julia

intersect

(

A, B

)

Set

{

String

}

with

3

elements:

 

"blue"

 

"green"

 

"red"

Difference: elements that belong to A but not to B:

Example

julia

setdiff

(

A, B

)

Set

{

String

}

with

1

element:

 

"black"

In addition there is the subset test function issubset() (operator ⊆) and issetequal() for testing whether two sets are equal:

Example

julia

Set

(

[

1

,

2

]

)

⊆

Set

(

[

1

,

2

,

3

]

)

true

julia

issubset

(

Set

(

[

1

,

2

]

)

,

Set

(

[

1

,

2

,

3

]

)

)

true

julia

issetequal

(

Set

(

[

1

,

2

]

)

,

Set

(

[

2

,

1

]

)

)

   

Independent of order

true

Tip:union, intersect, and setdiff also apply to arrays and are often used for fast deduplication: unique(A) returns the array with duplicate elements removed.


Quick reference to common dictionary functions

function Description
D[k] Get the value for key k; throws KeyError when it does not exist
get(D, k, default) Get the value; returns default when the key does not exist
get!(D, k, default) Get the value; when the key does not exist, write default and return it
haskey(D, k) Check whether a key exists
delete!(D, k) Delete a key-value pair
pop!(D, k) Delete a key-value pair and return the value
keys(D) / values(D) All keys / all values
length(D) Number of key-value pairs
merge(D1, D2) Merge dictionaries; the latter overrides the former