Data Collections: Arrays, Tuples & Dictionaries
8 min read
Data Collections: Arrays, Tuples & Dictionaries коллекции данных
Welcome, future Julia maestro! 🎶 In the world of programming, we rarely work with single pieces of data. Instead, we deal with collections of information. Think about a shopping list, a phone book, or a spreadsheet of monthly expenses. Julia, being the high-performance language that it is, provides a fantastic toolkit of data collections to handle these scenarios with grace and speed.
This guide will walk you through the most common and powerful data collections in Julia: Arrays, Tuples, and Dictionaries. We'll start with the basics and build our way up, focusing on what you'll actually use in the real world. So grab your favorite beverage, and let's dive in! ☕
Arrays and Vectors: The Backbone of Julia 🦴
The Problem: Imagine you're building a simple game and need to keep track of a player's high scores. You could create a bunch of separate variables like score1, score2, score3, but what happens when you want to find the highest score or calculate the average? It gets messy, fast. You need a way to store a list of related items.
The Solution: An Array! An array is an ordered collection of elements. In Julia, the most common type of array is a Vector, which is just a fancy name for a one-dimensional array. Think of it as a single column in a spreadsheet.
An array in Julia is a mutable, ordered collection of elements. This means you can change the elements, add new ones, and remove others after the array has been created.
Creating Arrays and Vectors
Let's get our hands dirty. The most common way to create a vector is by using square brackets [] with comma-separated values.
# A Vector of integers
high_scores = [98, 102, 76, 115, 99]
# A Vector of strings
player_names = ["Alice", "Bob", "Charlie"]
# A Vector of mixed types (though usually, you'll want to stick to one type)
mixed_bag = [42, "hello", 3.14]Fun Fact: Julia is "column-major," which might sound like a military rank, but it just means that it stores arrays in memory by columns first. This little detail is one of the reasons Julia is so speedy with numerical calculations!
Accessing and Modifying Elements
What good is a list if you can't get to the items in it? Julia uses 1-based indexing, which might feel a bit different if you're coming from a language like Python or JavaScript where indexing starts at 0. It's a nod to its mathematical roots.
# Get the first high score
first_score = high_scores[1] # This will be 98
# Get the third player's name
third_player = player_names[3] # This will be "Charlie"
# You can also use `end` to get the last element
last_score = high_scores[end] # This will be 99
# Let's update a score. Maybe Alice got a new high score!
player_names[1] = "Super Alice"
high_scores[1] = 120Common and Useful Functions
Here are a few functions you'll find yourself using all the time with arrays:
push!: Adds an element to the end of an array. The!at the end is a Julia convention indicating that the function modifies its argument.pop!: Removes the last element from an array and returns it.length: Gets the number of elements in an array.sort!: Sorts the array in place.sum,mean,maximum,minimum: For your mathematical needs.
# Let's add a new score
push!(high_scores, 88)
# Now high_scores is [120, 102, 76, 115, 99, 88]
# How many scores do we have?
num_scores = length(high_scores) # This will be 6
# Let's sort them to see the best score
sort!(high_scores, rev=true) # rev=true sorts in descending order
# The highest score is now at the beginning
highest_score = high_scores[1]Multidimensional Arrays and Matrix Operations 🔢
The Problem: A single list of scores is great, but what if you want to represent a tic-tac-toe board, an image, or a grid of data? A single-dimensional array just won't cut it.
The Solution: A Multidimensional Array, or more specifically for two dimensions, a Matrix. A matrix is essentially a grid of elements, with rows and columns.
Creating Matrices
You can create a matrix in a few ways. The most direct is to use square brackets with spaces to separate elements in a row and semicolons to separate rows.
# A 3x3 matrix representing a tic-tac-toe board
# Let's say 1 is 'X', -1 is 'O', and 0 is an empty space
tic_tac_toe_board = [1 0 -1;
1 -1 0;
-1 1 0]
# You can also create matrices of a certain size filled with a default value
# A 2x3 matrix of zeros
zeros_matrix = zeros(Int, 2, 3) # Creates a 2x3 matrix of integers initialized to 0
# A 4x4 matrix of ones
ones_matrix = ones(Float64, 4, 4) # Creates a 4x4 matrix of 64-bit floats initialized to 1.0Matrix Operations
This is where Julia truly shines, especially for those in scientific computing and data science. Basic mathematical operations work element by element.
matrix_a = [1 2; 3 4]
matrix_b = [5 6; 7 8]
# Element-wise addition
sum_matrix = matrix_a + matrix_b
# Element-wise multiplication
elementwise_product = matrix_a .* matrix_b # Note the dot `.` for element-wise operations
# For true matrix multiplication, you use `*`
matrix_product = matrix_a * matrix_bUnder the Hood: When you perform matrix operations, Julia calls highly optimized, low-level libraries (like BLAS and LAPACK) to do the heavy lifting. This is a significant reason for its impressive performance in numerical tasks.
Tuples and NamedTuples: Lightweight and Fast Data 🚀
The Problem: Sometimes you have a fixed collection of items that you don't want to change. For example, the RGB values of a color, or the coordinates of a point. Using an array for this is possible, but it's like using a sledgehammer to crack a nut. Arrays are mutable, meaning their values can change, which might not be what you want.
The Solution: A Tuple. A tuple is an ordered, immutable collection of elements. "Immutable" is a fancy way of saying once it's created, you can't change it. This makes them more memory-efficient and faster for certain operations than arrays.
Creating Tuples
Tuples are created using parentheses ().
# A tuple representing an RGB color
red_color = (255, 0, 0)
# A tuple representing a point in 3D space
a_point = (10.5, -3.2, 5.0)
# You can access elements just like with arrays
red_value = red_color[1] # This is 255Because tuples are immutable, you can't do this: red_color[1] = 128 # This will throw an error!
NamedTuples: Tuples with a Sense of Style
The Problem: With a regular tuple like (255, 0, 0), you have to remember that the first element is red, the second is green, and the third is blue. This can get confusing.
The Solution: A NamedTuple. It's just like a tuple, but each element has a name.
# A NamedTuple for our color
red_color_named = (r=255, g=0, b=0)
# Now you can access elements by their name!
red_value = red_color_named.r # Much clearer!NamedTuples are a fantastic way to make your code more readable without sacrificing performance.
Dictionaries and Sets: Key-Value Data Management 🔑
The Problem: Imagine you need to store the phone numbers of your friends. You could use an array, but then you'd have to search through it to find a specific person's number. This is inefficient, especially if you have a lot of friends!
The Solution: A Dictionary (often called a Dict in Julia). A dictionary stores a collection of key-value pairs. You use a unique key to look up a corresponding value. This is much faster than searching through a list.
Creating and Using Dictionaries
You can create a dictionary using the Dict() constructor.
# A dictionary of phone numbers
phone_book = Dict(
"Alice" => "555-1234",
"Bob" => "555-5678",
"Charlie" => "555-9999"
)
# You can also create an empty dictionary and add to it
# person_ages = Dict{String, Int}()
# person_ages["Alice"] = 30
# Accessing a value is easy
alices_number = phone_book["Alice"]
# Adding a new entry
phone_book["David"] = "555-4321"
# Checking if a key exists
haskey(phone_book, "Bob") # returns trueSets: The Unordered, Unique Collection
The Problem: What if you just want to store a collection of unique items, and you don't care about the order? For example, a list of unique tags for a blog post.
The Solution: A Set. A set is an unordered collection of unique elements.
# A set of tags
tags = Set(["julia", "programming", "guide", "julia"])
# Notice that "julia" was only added once, even though we provided it twice.
# The set is now {"guide", "julia", "programming"} (the order is not guaranteed)
# Common set operations
another_set_of_tags = Set(["data science", "julia"])
# Union: all unique tags from both sets
union(tags, another_set_of_tags)
# Intersection: tags that are in both sets
intersect(tags, another_set_of_tags) # This will be {"julia"}Real-World Scenario: Imagine you are building a system to manage user permissions for a website. A dictionary could be used to store each user's role ("user_id" => "admin"). Sets could be used to define the permissions for each role (admin_permissions = Set(["edit_posts", "delete_users"])).
Further Reading 📚
To continue your journey, here are some official documentation links:
Challenge
Challenge: Student Roster Analysis
Your task is to write a Julia function called analyze_roster that processes a list of student records. This function will perform several data aggregation and transformation tasks using Julia's core collection types.
Function Signature:analyze_roster(roster::Vector{Dict})
Input:
The function receives one argument, roster, which is a Vector of Dicts. Each Dict represents a student and has the following structure:
"id": AnIntrepresenting the student's unique ID."name": AStringfor the student's name."scores": ADict{String, Int}where keys are subject names and values are the integer scores for those subjects.
Requirements:
- Calculate the average score for each student.
- Determine each student's final status. A student passes if their average score is 60 or greater, otherwise they fail.
- Collect all unique subject names from across all students.
- Create a leaderboard of students, sorted in descending order by their average score.
Return Value:
The function must return a single NamedTuple with the following three fields:
statuses: ADict{Int, String}that maps each student'sidto their status string ("Pass"or"Fail").subjects: ASet{String}containing all unique subject names present in the roster.leaderboard: AVectorofNamedTuples, where eachNamedTuplehas two fields:name::Stringandaverage::Float64. This vector must be sorted in descending order based on theaveragescore.
Expected result
The function should process the sample roster provided in the initial code and return a NamedTuple that contains the calculated student statuses, the set of unique subjects, and a sorted leaderboard.
Given the sample input, the exact output should be a NamedTuple equivalent to this:
(
statuses = Dict(104 => "Pass", 102 => "Fail", 101 => "Pass", 103 => "Pass"),
subjects = Set(["Math", "Art", "Science", "History"]),
leaderboard = [
(name = "Alice", average = 89.0),
(name = "Charlie", average = 87.0),
(name = "Diana", average = 81.66666666666667),
(name = "Bob", average = 55.0)
]
)Note: The order of key-value pairs in the statuses Dict and elements in the subjects Set may vary, as they are unordered collections. However, the contents must be identical, and the leaderboard vector must be in the exact specified order.