Data Types - Dictionaries, Sets and Booleans

While reading this series, you should type out the code along with the teacher and look at the output of print to deepen your understanding.

1 Dictionaries

1. Basic Introduction to the Dictionary Type

A dictionary can be used to store a person’s information: name, gender, age. These are clearly multiple values, and since we’re storing multiple values, we could perfectly well store them in the list we just learned about, as follows:

# In that case, why do we still need dictionaries?
info=['albert','male',18]
# The purpose of defining a list is not only storage; we also have to consider retrieving values. If I want to get this person's age, I can use
info[2]
# But this relies on already knowing that the age is stored in the 3rd position; only then do we know that index 2 corresponds to age, i.e.:
#      # name, sex, age
info=['albert','male',18]
"""
But this is purely an assumption; nothing actually stipulates that the third position stores the age.
So we need a type that can both store multiple values of any type and strictly define the mapping of values,
for example key=value, and this is where dictionaries come in
"""

Dictionaries are used to store multiple values, where each value has a unique corresponding key, which makes retrieving values more convenient and efficient. The format for defining a dictionary is as follows:

# Inside {}, separated by commas, you can store multiple key:value pairs; the key is usually a string, and the value can be of any type
info={'name':'albert','age':18,'sex':18} 
# info=dict({'name':'albert','age':18,'sex':18})

A dictionary can store multiple values, is unordered, is a mutable type, and is not hashable.

2. Common Methods of the Dictionary Type

(1) Adding Elements

Using a key-value pair

l1 = {
    'name': 'albert',
    'age': 18,
    'gender': 'male'
}
l1['hobbies'] = "music"
print(l1)

Constructing a dictionary with fromkeys

"""
The first argument is iterated over to produce the dictionary's keys, and the second argument is the value;
multiple keys can map to this value in turn, there can be just one key, and there can also be no value
"""
a = l1.fromkeys(l1,'I am Albert') 
print(a)

b = dict.fromkeys('name')  # There must be an iterable to serve as the dictionary's keys
print(b)

b = dict.fromkeys('e')  # This can also be iterated
print(b)
# b = dict.fromkeys(1) # Error: numeric types are not iterable

b = dict.fromkeys([1,2,3,])
print(b)

(2) Deleting Elements

del deletes by the dictionary’s key

l1 = {
    'name': 'albert',
    'age': 18,
    'gender': 'male'
}

del l1['name']
print(l1)

Deleting with pop or popitem

l1 = {
    'name': 'albert',
    'age': 18,
    'gender': 'male'
}

res = l1.pop('name')  # Delete the value of the specified key and get a return value
print(res)
print(l1)

res2 = l1.popitem()  # Return and delete an arbitrary key-value pair from the dictionary (usually the last pair).
# If the dictionary is already empty and this method is called, a KeyError exception is raised.
print(res2)
print(l1)

(3) Modifying Elements

Using a key-value pair

l1 = {
    'name': 'albert',
    'age': 18,
    'gender': 'male','3':3,
}

l1['name'] = '马一特'
print(l1)

Using setdefault or update; their usage and differences are as follows:

setdefault only adds, it doesn’t modify

d1 = {
    'name': 'albert',
    'age': 18,
}

d1.setdefault('name', 'Albert')
d1.setdefault('gender', 'male')
print(d1)

update both adds and modifies

d1 = {
    'name': 'albert',
    'age': 18,
}

d1.update({'name': 'Albert', 'gender': 'male'})  # Note the different way of passing arguments
print(d1)

(4) Looking Up Elements

Looking up by key

l1 = {
    'name': 'albert',
    'age': 18,
    'gender': 'male'
}

a = l1['name']
print(a)

Looking up with the get method

l1 = {
    'name': 'albert',
    'age': 18,
    'gender': 'male'
}

a = l1.get('hobbies')   # No error if not found
print(a)

Enumerating with enumerate

d1 = {
    'name': 'albert',
    'age': 18,
    'gender': 'male',
    '3':3,
}

for a in enumerate(d1):
    print(a)

Using methods such as .keys(), .values(), .items()

d1 = {
    'name': 'albert',
    'age': 18,
    'gender': 'male',
    '3':3,
}

a = d1.keys()
print(a)
print(list(a)[0])

a = d1.values()
print(a)
print(list(a)[0])

a = d1.items()
print(a)
print(list(a)[0])

Iterating with a for loop

d1 = {
    'name': 'albert',
    'age': 18,
    'gender': 'male',
    '3':3,
}

for k,v in d1.items():
    print(k,v)

(5) Membership and Length Operations

Refer to the operations for lists. Membership tests are based on the dictionary’s keys, not its values; length operations can be used as a reference as well

2 The Set Type

Inside curly braces, multiple elements separated by commas are used to store multiple values, and they are unordered, so these values can’t be used for retrieval. However, we can use a set for deduplication (for example, removing duplicate elements from a list) and relational operations.

# The elements of a set follow three principles:
             1: Each element must be of an immutable type (usable as a dictionary key)
             2: No duplicate elements
             3: Unordered
# Note that the purpose of a set is to store different values together, and different sets are used for relational operations; there's no need to fuss over individual values in a set

The set type can store multiple values, is unordered, is a mutable type, and is not hashable.

Relational operations exercise

Given the following two sets: piano is the set of names of students enrolled in the piano course, and violin is the set of names of students enrolled in the violin course
  piano={'albert','孙悟空','周星驰','朱茵','林志玲'}
  violin={'猪八戒','郭德纲','林忆莲','周星驰'}
  1. Find the set of names of students enrolled in both the piano and violin courses
  2. Find the set of names of all enrolled students
  3. Find the names of students enrolled only in the piano course
  4. Find the set of names of students not enrolled in both courses at the same time

Reference answers

# Find the set of names of students enrolled in both the piano and violin courses
print(piano & violin)
# Find the set of names of all enrolled students
print(piano | violin)
# Find the names of students enrolled only in the piano course
print(piano - violin)
# Find the set of names of students not enrolled in both courses at the same time
print(piano ^ violin)

3 The Boolean Type

In Chinese, a computer is commonly called an “electric brain”. That is, when we write programs for the computer to run, we should make the computer come infinitely close to the human brain; in other words, whatever the human brain can do, the computer should be able to do. The main functions of the human brain are data processing and logical operations, and the boolean type here simulates human logical operations: when a condition is judged to hold, it is marked with True, and when it does not hold, it is marked with False.

# Boolean values: one True and one False
>>> a=3
>>> b=5
>>> a > b # If it doesn't hold, it's False, i.e. false
False
>>> a < b # If it holds, it's True, i.e. true
True
# Next we can do different things depending on the result of the condition:
if a > b:
   print(a is bigger than b )
else:
   print(a is smaller than b )
# The above is pseudocode, but it means the computer can already, like the human brain, perform different actions depending on different results of a judgment.

Key points about the boolean type

# Every data type has its own boolean value
1. In three cases the boolean value is False: None, 0, and empty (empty string, empty list, empty dictionary, etc.)
2. Everything else is true

Mutable and immutable types (key point)

# 1. Mutable types: if the value can change while the id stays the same, it is called a mutable type, such as lists and dictionaries
# 2. Immutable types: if the id changes as soon as the value changes, it is called an immutable type (a changed id means new memory space has been allocated)