Dictionary is a collection of related data pairs. For example, if we want to store the age of five users, we can store them in a dictionary.
The following topics are discussed below:
1. Declaring a dictionary
a. The first method
b. The second method
2. Accessing individual items in a dictionary
3. Modifying items in a dictionary
4. Declaring an empty dictionary
5. Adding items in a dictionary
6. Removing items in a dictionary
Declaring a dictionary
The first method
To declare a dictionary, we write dictionaryName = {dictionary key: data}, with the requirement that dictionary keys must be unique (within one dictionary). That is, you cannot declare a dictionary as myDictionary = {"Peter":38, "John":51, "Peter":13}. This is because "Peter" is used as the dictionary key twice.
Example:
userNameAndAge ={"Peter":38, "John":51, "Alex":13, "Alvin":"Not Available"}
The second method
We can also declare a dictionary using the dict() method. To declare the userNameAndAge dictionary above, we write
userNameAndAge = dict(Peter = 38, John = 51, Alex = 13, Alvin = "Not Available")
When we use this method to declare a dictionary, we use parentheses instead of curly braces and do not put quotation marks for the keys.
Accessing individual items in a dictionary
To access individual items in the dictionary, we use the dictionary key, which is the first value in the {dictionary key: data} pair. For example, to get John's age, we write userNameAndAge["John"]. We will get the value 51.
Modifying items in a dictionary
To modify items in a dictionary, we write dictionaryName[dictionary key of item to be modified] = new data. For example, to modify the "John":51 pair, we write userNameAndAge["John"] = 21. The dictionary now becomes userNameAndAge ={"Peter":38, "John":21, "Alex":13, "Alvin":"Not Available"}.
Declaring an empty dictionary
We can also declare a dictionary without assigning any initial values to it. We simply write dictionaryName = {}. This is an empty dictionary with no items in it.
Adding items in a dictionary
To add items in a dictionary, we write dictionaryName[dictionary key] = data. For example, if we want to add "Joe":40 to our dictionary, we write userNameAndAge["Joe"] = 40. The dictionary now becomes userNameAndAge ={"Peter":38, "John":51, "Alex":13, "Alvin":"Not Available", "Joe":40}.
Removing items in a dictionary
To remove items from a dictionary, we write del userNameAndAge["Alex"]. The dictionary now becomes userNameAndAge ={"Peter":38, "John":51, "Alvin":"Not Available", "Joe":40}.
No comments:
Post a Comment