Python 字典 (dictionary) update() 方法
1. update() 函数
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# yongqiang cheng
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import sys
import cv2
import numpy as np
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
current_directory = os.path.dirname(os.path.abspath(__file__))
print(16 * "++--")
print("current_directory:", current_directory)
print(16 * "++--")
polylines = [[1024, 1, 2, 3, 4], [2048, 1, 2, 3, 4, 5, 6]]
polylines_dict = {}
for pline in polylines:
pline_id = pline[0]
polylines_dict.update({pline_id: pline[1:]})
pass
print("polylines_dict:", polylines_dict)
for idx, pline in enumerate(polylines):
print("idx: pline ->", idx, pline)
pass
/usr/bin/python3.5 /home/strong/sunergy_moonergy/object_counter/yongqiang.py
++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--
current_directory: /home/strong/sunergy_moonergy/object_counter
++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--
polylines_dict: {1024: [1, 2, 3, 4], 2048: [1, 2, 3, 4, 5, 6]}
idx: pline -> 0 [1024, 1, 2, 3, 4]
idx: pline -> 1 [2048, 1, 2, 3, 4, 5, 6]
Process finished with exit code 0
2. 具有相同的键会直接替换成 update() 的值
字典是一种动态结构,可随时在其中添加键-值对。在 Python 中,字典是一系列键—值对。每个键都与一个值相关联。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# yongqiang cheng
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import os
import sys
import cv2
import numpy as np
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
current_directory = os.path.dirname(os.path.abspath(__file__))
print(16 * "++--")
print("current_directory:", current_directory)
print(16 * "++--")
dict_a = {1: 2, 2: 4}
dict_b = {1: 3, 3: 9}
print("dict_a:", dict_a)
print("dict_b:", dict_b)
dict_b.update(dict_a)
print("dict_b:", dict_b)
/usr/bin/python3.5 /home/strong/sunergy_moonergy/object_counter/yongqiang.py
++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--
current_directory: /home/strong/sunergy_moonergy/object_counter
++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--
dict_a: {1: 2, 2: 4}
dict_b: {1: 3, 3: 9}
dict_b: {1: 2, 2: 4, 3: 9}
Process finished with exit code 0