使用列表作为值,列表将允许您附加新项目:
>>> dic = {'PhysicalDrive0': ['0', '1', '2'], 'PhysicalDrive1': ['0', '1']}
>>> dic['PhysicalDrive0'].append('3')
>>> dic['PhysicalDrive1'].append('2')
>>> dic
{'PhysicalDrive1': ['0', '1', '2'], 'PhysicalDrive0': ['0', '1', '2', '3']}
要将值附加到缺少的键,您可以使用dict.setdefault
,如果键已经存在,那么它会将值附加到已经存在的列表,否则会创建一个带有空列表的键,然后将值附加到它。
演示:
#creates a new key PhysicalDrive3' and appends a value to it.
>>> dic.setdefault('PhysicalDrive3', []).append('3')
>>> dic
{'PhysicalDrive1': ['0', '1', '2'], 'PhysicalDrive0': ['0', '1', '2', '3'], 'PhysicalDrive3': ['3']}
>>> dic.setdefault('PhysicalDrive1', []).append('5')
>>> dic
{'PhysicalDrive1': ['0', '1', 2, '5'], 'PhysicalDrive0': ['0', '1', '2', 3], 'PhysicalDrive3': [3]}