-
向已有的字典键中添加值
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)
输出结果如下图所示: