[Python] basic data type - dictionary

 1. Definition

A dictionary is an unordered collection of key-value pairs

Dictionaries are surrounded by curly braces { }, each key-value pair is separated by a comma, and each key and value is separated by a colon

Dictionaries are dynamic , elements can be added or removed at any time

The key in the dictionary does not allow repeated elements, and the value allows repeated elements

Two, create

  • Create key-value pairs by filling them in curly braces
  • Created by the constructor dict()
  • Created via dictionary comprehension
# 大括号填充键值对
dc1 = {}
print(dc1)            # 输出:{}
dc1 = {'name': 'Andy', 'age': 18}
print(dc1)            # 输出:{'name': 'Andy', 'age': 18}

# 构造方法dict()创建
dc2 = dict()
print(dc2)            # 输出:{}
dc2 = dict(name = 'Andy', age = 18)    # 关键字参数赋值
print(dc2)            # 输出:{'name': 'Andy', 'age': 18}
dc2 = dict((('name', 'Andy'), ('age', 18)))     
print(dc2)            # 输出:{'name': 'Andy', 'age': 18}

# 字典推导式创建
dc3 = {k: v for k, v in {('name', 'Andy'), ('age', 18)}}
print(dc3)            # 输出:{'name': 'Andy', 'age': 18}

3. Dictionary usage

1. Operating elements

Writing method: dict[key] = value

Add element if key does not exist, modify element if key already exists

dc = {'name': 'Andy', 'age': 18}
dc['age'] = 20
print(dc)            # 输出:{'name': 'Andy', 'age': 20}
dc['gender'] = 'male'
print(dc)            # 输出:{'name': 'Andy', 'age': 20, 'gender': 'male'}

2. Nested dictionary

Dictionary values ​​can be in dictionary format

dc = {'name': 'Andy', 'age': 18, 'course': {'python': 90, 'java': 80}}
print(dc['course']['python'])        # 输出:90
dc['course']['java'] = 100
print(dc)    # 输出:{'name': 'Andy', 'age': 18, 'course': {'python': 90, 'java': 100}}

4. Dictionary method 

1、keys()

Returns a new view object consisting of the dictionary keys

Writing method: dict.keys()

Entry parameters: none

Returns: a new view object consisting of the dictionary keys

dc = {'name': 'Andy', 'age': 18}
print(dc.keys())        # 输出:dict_keys(['name', 'age'])

# 遍历查看所有的键
for i in dc.keys():
    print(i)            # 输出:name
                        # 输出:age
# 将试图对象转化为列表
print(list(dc.keys()))  # 输出:['name', 'age']

2、values()

Returns a new view object consisting of dictionary values

Writing method: dict.values()

Entry parameters: none

Returns: a new view object consisting of dictionary values

dc = {'name': 'Andy', 'age': 18}
print(dc.values())        # 输出:dict_values(['Andy', 18])

# 遍历查看所有的键
for i in dc.values():
    print(i)              # 输出:'Andy'
                          # 输出:18
# 将试图对象转化为列表
print(list(dc.values()))  # 输出:['Andy', 18]

3、items()

Returns a new view object consisting of dictionary items (key-value pairs)

Writing method: dict.items()

Entry parameters: none

Returns: a new view object consisting of dictionary items (key-value pairs)

dc = {'name': 'Andy', 'age': 18}
print(dc.items())        # 输出:dict_items([('name', 'Andy'), ('age', 18)])

# 遍历查看所有的键
for i in dc.items():
    print(i)              # 输出:('name', 'Andy')
                          # 输出:('age', 18)
# 将试图对象转化为列表
print(list(dc.items()))  # 输出:[('name', 'Andy'), ('age', 18)]

4、get()

Get the value corresponding to the specified key

Writing method: dict.get(key)

Input parameter: the key key of the dictionary

Return: If the key exists in the dictionary, return the value corresponding to the key. Returns None if key does not exist in the dictionary

Target element does not exist and KeyError will not be raised

dc = {'name': 'Andy', 'age': 18}
print(dc.get('name'))            # 输出:Andy
print(dc.get('course'))          # 输出:None

5、update()

Update the dictionary with the key-value pairs from dict, overwriting the original key and value

Writing method: dict.update(dict)

Input parameter: dictionary object dict

return: None

dc = {'name': 'Andy', 'age': 18}
print(dc.update({'age': 20}))   # 输出:None
print(dc)                       # 输出:{'name': 'Andy', 'age': 20}
dc.update({'course':['python', 'java']})
print(dc)            # 输出:{'name': 'Andy', 'age': 20, 'course': ['python', 'java']}

6、pop()

Delete the key-value pair of the specified key and return the corresponding value

Writing method: dict.pop(key)

Input parameter: key

Return: If the key exists in the dictionary, return the value corresponding to the key

Raises KeyError if key does not exist in the dictionary

dc = {'name': 'Andy', 'age': 18}
print(dc.pop('age'))    # 输出:18
print(dc)               # 输出:{'name': 'Andy'}
dc.pop('course')        # 输出:KeyError: 'course'

Five, dictionary derivation 

A dictionary can be constructed from any iterable object with key-value pairs as elements

data = [('a', 1), ('b', 2), ('c', 3)]
# for循环创建字典
dc1 = {}
for k, v in data:
    if v > 1:
        dc1[k] = v ** 2
print(dc1)          # 输出:{'b': 4, 'c': 9}

# 字典推导式创建字典
dc2 = {k:v**2 for k, v in data if v > 1}
print(dc2)          # 输出:{'b': 4, 'c': 9}
# 无else时,if在for循环之后
data = {'a': 1, 'b': 2, 'c': 3}
# for循环创建字典
dc1 = {}
for k, v in data.items():
    if v > 2:
        dc1[k] = v ** 2
    else:
        dc1.update({k:v})
print(dc1)          # 输出:{'a': 1, 'b': 2, 'c': 9}

# 字典推导式创建字典
dc2 = {k:v**2 if v > 2 else v for k, v in data.items()}
print(dc2)          # 输出:{'a': 1, 'b': 2, 'c': 9}
# 有else时,if…else在for循环之前

Guess you like

Origin blog.csdn.net/Yocczy/article/details/132403574