[100 days proficient in python] Day9: Data structure_dictionary, collection

Table of contents

 Table of contents

1 dictionary     

1.1 Examples of basic operations on dictionaries

1.2 Dictionary comprehension

2 sets 

 2.1 Examples of common operations on collections

3 Differences between lists, tuples, dictionaries, and sets


1 dictionary     

          In Python, a dictionary (Dictionary) is an unordered data structure used to store a collection of key-value pairs. Each key (Key) must be unique, and the value (Value) can be any type of data. Dictionaries are defined using braces " {} ", keys and values ​​are separated by colons " : ", and each pair of key-value pairs is separated by commas "  ,”. The keys of a dictionary must be immutable data types (such as integers, strings, and tuples), and the values ​​can be of any data type, including lists, dictionaries, etc.

Dictionary diagram:

1.1 Examples of basic operations on dictionaries

        Including creating, accessing, modifying and deleting the values ​​in the dictionary, getting the keys and values ​​of the dictionary, traversing the dictionary

# 创建一个字典
my_dict = {"name": "Alice", "age": 30, "email": "[email protected]"}

# 访问字典中的值
print(my_dict["name"])  # 输出: Alice
print(my_dict["age"])   # 输出: 30
print(my_dict["email"]) # 输出: [email protected]

# 修改字典中的值
my_dict["age"] = 31

# 添加新的键值对
my_dict["address"] = "123 Main St"

# 删除键值对
del my_dict["email"]

# 检查键是否存在
if "name" in my_dict:
    print("Name exists in the dictionary.")

# 获取字典中所有键
keys = my_dict.keys()
print(keys) # 输出: dict_keys(['name', 'age', 'address'])

# 获取字典中所有值
values = my_dict.values()
print(values) # 输出: dict_values(['Alice', 31, '123 Main St'])

# 获取字典中所有键值对
items = my_dict.items()
print(items) # 输出: dict_items([('name', 'Alice'), ('age', 31), ('address', '123 Main St')])

# 遍历字典
for key, value in my_dict.items():
    print(key, value)
# 输出:
# name Alice
# age 31
# address 123 Main St

Dictionaries are often used in Python to store data with relationships, such as storing user information, configuration options, and so on. Due to its efficient lookup and modification properties, dictionaries are one of the commonly used data structures in Python programming.

1.2 Dictionary comprehension

        Apply dictionary comprehension to create a dictionary python based on name and constellation

# 假设有两个列表,一个是名字列表,一个是星座列表
names = ["张三", "李四", "王五", "赵六"]
constellations = ["白羊座", "双子座", "狮子座", "天蝎座"]

# 使用字典推导式创建字典,将名字作为键,星座作为值
name_constellation_dict = {name: constellation for name, constellation in zip(names, constellations)}

# 打印创建的字典
print(name_constellation_dict)

 Output result:

{'张三': '白羊座', '李四': '双子座', '王五': '狮子座', '赵六': '天蝎座'}

2 sets 

        In Python, a set (Set) is an unordered and non-repetitive data structure. The elements in the collection must be immutable data types, such as numbers, strings, tuples, etc., and cannot contain mutable data types, such as lists, dictionaries, etc. Sets are defined using braces {}and elements are separated by commas ,.

        The main feature of a set is that it does not allow duplicate elements, so it can be used to remove duplicates. In addition, sets support some basic set operations, such as union, intersection, difference, and so on.

 2.1 Examples of common operations on collections

        Including creation, addition and deletion of collection elements, traversal of collections, intersection and difference of collections.

# 创建一个集合
my_set = {1, 2, 3, 4, 5}

# 添加元素到集合
my_set.add(6)

# 删除集合中的元素
my_set.remove(3)

# 检查元素是否存在于集合中
if 4 in my_set:
    print("4 exists in the set.")

# 获取集合的长度
length = len(my_set)
print("Length of the set:", length)

# 遍历集合
for item in my_set:
    print(item)

# 创建另一个集合
other_set = {4, 5, 6, 7}

# 计算并集
union_set = my_set | other_set
print("Union set:", union_set)

# 计算交集
intersection_set = my_set & other_set
print("Intersection set:", intersection_set)

# 计算差集
difference_set = my_set - other_set
print("Difference set:", difference_set)

3 Differences between lists, tuples, dictionaries, and sets

  1. List (List):

    • A list is an ordered data structure that can contain elements of any type, including integers, strings, lists, tuples, dictionaries, and more.
    • Lists are defined using square brackets [ ]and elements are separated by commas ,.
    • Lists are mutable, and elements can be modified or deleted through indexes, and can also be added, inserted, and deleted through various methods.
    • Lists are allowed to contain duplicate elements.
  2. Tuple:

    • Tuples are also ordered data structures, similar to lists, but tuples are immutable and cannot be modified once created.
    • Tuples ( )are defined using parentheses and elements are separated by commas ,.
    • Once a tuple is created, its elements cannot be modified, so it can be used as a key of a dictionary or an element of a collection, while a list cannot.
  3. Dictionary (Dictionary):

    • A dictionary is a data structure of key-value pairs used to store associations.
    • Dictionaries are defined using curly braces { }, key-value pairs are separated by colons :, and key-value pairs are separated by commas ,.
    • The keys in the dictionary must be immutable data types, such as strings, numbers, tuples, while the values ​​can be any type of data.
    • Dictionaries are mutable, and values ​​can be modified, added, or removed by key.
  4. Collection (Set):

    • A collection is an unordered and non-repetitive data structure that can only contain immutable elements, and cannot contain variable data types such as lists and dictionaries.
    • Sets are defined using curly braces { }and elements are separated by commas ,.
    • Collections are mutable and can be added, deleted, etc. through methods.
    • Sets can be used to remove duplicates in a list, and to perform some basic set operations such as union, intersection, difference, etc.

Guess you like

Origin blog.csdn.net/qq_35831906/article/details/131857972