Programming/Dictionaries: Difference between revisions

From Dev Wiki
Jump to navigation Jump to search
(Formatting)
m (Brodriguez moved page Dictionaries to Programming/Dictionaries)
 

Latest revision as of 17:25, 25 October 2020

Similarly to Arrays, dictionaries are data structures meant to store groups of items.

Conceptually, the biggest difference is that dictionary values are accessed via a "key", rather than an index number.
This key can be anything the programmer desires, such as a string, an integer, etc. The only stipulation is that each unique key refers to a single value. Each one of these entries is generally referred to as a "Key-Value" pair.

Furthermore, unlike arrays, most languages automatically handle dictionary size for you in the background.

Generally speaking, the syntax for dictionaries in most languages uses { } (braces/curly brackets).


Core Operations

Note that syntax for these will vary wildly depending on the language. See documentation of your specific language for syntax details.

Initialization

Generally speaking, dictionaries can be initialized as empty:

my_dict = {}

Or with initial values:

my_dict = {
    "Ice Cream" = 50,
    "Burgers" = 56,
    "Pizza" = 102,
}


Accessing a Key-Value Pair

For most languages, access a Key-Value pair by putting the key in [ ] (square brackets). Ex:

pizza_count = my_dict["Pizza"];

Adding a New Key-Value Pair

For most languages, a new Key-Value pair is established by combining an assignment statement and the above "access" syntax. Ex:

my_dict["Pizza"] = 103;

Removing a Key-Value Pair

Syntax for this tends to vary quite a bit. But two examples of removing the "Pizza" value from the dictionary are:

my_dict.Remove("Pizza");
del my_dict["Pizza"];