Python入門:字典
阿新 • • 發佈:2018-12-17
-
向已有的字典鍵中新增值
for j in range(batch_size):
if h[j] in fast.keys():
fast[h[j]].append((img_name[j], temp_f7[j, :].tolist()))
else:
# 需要注意的是此處的值設定為list,否則不能呼叫append函式
fast[h[j]] = [(img_name[j], temp_f7[j, :].tolist())]
-
字典巢狀
fast.setdefault(1, {})['a'] = [1,2,3,4,5] fast.setdefault(1, {})['b'] = 6 fast.setdefault(1, {})['c'] = '7' fast.setdefault(1, {})['d'] = (8) ''' {1: {'a': [1, 2, 3, 4, 5], 'b': 6, 'c': '7', 'd': 8}} '''
-
遍歷字典
a = {'a': 1, 'b': 2, 'c': 3} print('--------------遍歷key值(1)--------------') for key in a: print(key, a[key]) print('--------------遍歷key值(2)--------------') for key in a.keys(): print(key, a[key]) print('--------------遍歷value值---------------') for value in a.values(): print(value) print('--------------遍歷鍵值對(1)--------------') for key, value in a.items(): print(key, value) print('--------------遍歷鍵值對(2)--------------') for (key, value) in a.items(): print(key, value) print('--------------遍歷字典項-----------------') for key_value in a.items(): print(key_value)
輸出結果如下圖所示: