1 字典dict遍历的方法

Python中,可以使用遍历键、遍历值、遍历键值对字典进行遍历。

1.1 遍历字典的键

(1) for key in dict遍历字典的键

# -*- coding: utf-8 -*-

if __name__ == '__main__':
    test_dict = {
        'Net':'ResNet18',
        'epoch':150,
        'lr':0.001
    }

    for key in test_dict:
        print('键key:{} 值value:{}'.format(key,test_dict[key]))

输出

键key:Net 值value:ResNet18
键key:epoch 值value:150
键key:lr 值value:0.001

(2) for key in dict.keys()遍历字典的键

# -*- coding: utf-8 -*-

if __name__ == '__main__':
    test_dict = {
        'Net':'ResNet18',
        'epoch':150,
        'lr':0.001
    }

    for key in test_dict.keys():
        print('键key:{} 值value:{}'.format(key,test_dict[key]))

输出

键key:Net 值value:ResNet18
键key:epoch 值value:150
键key:lr 值value:0.001

1.2 遍历字典的值

# -*- coding: utf-8 -*-

if __name__ == '__main__':
    test_dict = {
        'Net':'ResNet18',
        'epoch':150,
        'lr':0.001
    }

    for value in test_dict.values():
        print('值value:{}'.format(value))

1.3 遍历字典的键值对

(1) for item in dict.items()遍历字典的键值对

# -*- coding: utf-8 -*-

if __name__ == '__main__':
    test_dict = {
        'Net':'ResNet18',
        'epoch':150,
        'lr':0.001
    }

    for item in test_dict.items():
        print('键key:{} 值value:{}'.format(item[0],item[1]))

(2) for key,value in test_dict.items()遍历字典的键值对

# -*- coding: utf-8 -*-

if __name__ == '__main__':
    test_dict = {
        'Net':'ResNet18',
        'epoch':150,
        'lr':0.001
    }

    for key,value in test_dict.items():
        print('键key:{} 值value:{}'.format(key,value))

(3) 使用enumerate遍历字典的键值对

# -*- coding: utf-8 -*-

if __name__ == '__main__':
    test_dict = {
        'Net':'ResNet18',
        'epoch':150,
        'lr':0.001
    }

    for idx,(key,value) in enumerate(test_dict.items()):
        print('索引:{} 键key:{} 值value:{}'.format(idx,key,value))

输出

索引:0 键key:Net 值value:ResNet18
索引:1 键key:epoch 值value:150
索引:2 键key:lr 值value:0.001