1 嵌套
将很多个字典存储在列表中,或将列表作为值存储在字典中。
2 列表中存字典
创建3个字典alien_0,alien_1,alien_2;将字典存储在列表aliens中:
#创建字典
alien_0={'color':'green','points':5}
alien_1={'color':'yellow','points':10}
alien_2={'color':'red','points':15}
#列表中嵌套字典
aliens=[alien_0,alien_1,alien_2]
#打印
for alien in aliens:
print(alien)
运行结果:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
创建更多的字典,存入列表aliens中:
aliens=[];
for aliens_num in range(0,10):
new_aliens={'color':'green','point':5,'speed':'slow'}
aliens.append(new_aliens)
for alien in aliens[:4]:#打印前4个aliens
print(alien)
print('.....')
print(f"一共有{len(aliens)}个alien")
运行结果:
{'color': 'green', 'point': 5, 'speed': 'slow'}
{'color': 'green', 'point': 5, 'speed': 'slow'}
{'color': 'green', 'point': 5, 'speed': 'slow'}
{'color': 'green', 'point': 5, 'speed': 'slow'}
.....
一共有10个alien
3 字典中存列表
创建,字典中嵌套列表:
vehicle_info={'Number':1001,
'variable':['nmot_w','rl_w','miist_w']}
print(f"Vehicle {vehicle_info['Number']} measured variable: {vehicle_info['variable']}")
运行结果:
Vehicle 1001 measured variable: ['nmot_w', 'rl_w', 'miist_w']
4 相互嵌套
列表中嵌套字典,字典中嵌套列表:
#字典中嵌套列表
vehicle_info_0={'Number':1001,
'variable':['nmot_w','rlsol_w','miist_w']}
vehicle_info_1={'Number':1002,
'variable':['nmot_w','rl_w','miist_w']}
vehicle_info_2={'Number':1003,
'variable':['nmot_w','rlp_w','miist_w']}
vehicle_info_3={'Number':1004,
'variable':['nmot_w','rl_w','miist_w']}
#列表中嵌套字典
vehicle_infos=[vehicle_info_0,vehicle_info_1,vehicle_info_2,vehicle_info_3]
for vehicle_info in vehicle_infos:#遍历车辆列表
for value in vehicle_info['variable']:#遍历车辆列表中的测量变量
if value == 'rl_w':#寻找含有rl_w变量的车辆,并且打印出来
print(f"rl_w is within the {vehicle_info['Number']} measurement variable.")
运行结果:
rl_w is within the 1002 measurement variable.
rl_w is within the 1004 measurement variable.
字典嵌套字典:
#字典中嵌套列表
vehicle_info_0={'Number':1001,
'variable':['nmot_w','rlsol_w','miist_w']}
vehicle_info_1={'Number':1002,
'variable':['nmot_w','rl_w','miist_w']}
vehicle_info_2={'Number':1003,
'variable':['nmot_w','rlp_w','miist_w']}
vehicle_info_3={'Number':1004,
'variable':['nmot_w','rl_w','miist_w']}
#字典中嵌套字典
vehicle_infos= {
'jack':vehicle_info_0,
'allen':vehicle_info_1,
'lucy':vehicle_info_2,
'jhon':vehicle_info_3
}
for vehicle_info in vehicle_infos.keys():#遍历车辆所有者键值
if vehicle_infos[vehicle_info]['Number'] == 1003:#寻找1003编号的车辆所有者,并且打印出来
print(f"Vehicle 1003 is belone to {vehicle_info} .")
运行结果:
Vehicle 1003 is belone to lucy .