1.字典由‘{}’包含,其中都是一些键-值对,例如:
xxx={'people':'cql','age':18}
2.访问值时使用xxx['people']
3.添加键-值对:
xxx={'people':'cql','age':18}
xxx['car']='byd'
print(xxx)
输出则为:{'people':'cql','age':18,'car':'byd'}
所以有时候可以先创建一个空字典,然后再逐步向里面装键-值对。
4.改键-值对:
xxx['car']='cnm'
5.删除键-值对:
del xxx['car']
6.1遍历字典:
xxx={'people':'cql',
'age':18,
'car':'byd'}
for key,value in xxx.items():
print('\nkey:'+key)
print('\nvalue:'+value)
输出为:
key:people
value:cql
key:age
value:18
key:car
value:byd
6.2.1遍历字典的所有键(顺序不定):
xxx={'people':'cql',
'age':18,
'car':'byd'}
for name in xxx.keys():
print(name.title())
6.2.2遍历字典的所有键(按顺序):
xxx={'people':'cql',
'age':'18',
'car':'byd'}
for name in sorted(xxx.keys()):
print(name.title())
6.2.3遍历字典的所有值
6.2.3.1(显示重复项)
xxx={'people':'cql',
'age':'18',
'car':'byd',
'cars':'byd'}
for name in xxx.values():
print(name.title())
输出为:
cql
18
byd
byd
6.2.3.2(如集合般无重复)
xxx={'people':'cql',
'age':'18',
'car':'byd',
'cars':'byd'}
for name in set(xxx.values()):
print(name.title())
输出为:
cql
18
byd
7.字典列表
alien_0={'color':'green','points':5}
alien_1={'color':'red','points':10}
alien_2={'color':'yellow','points':15}
aliens=[alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)
7.1自动生成alien
aliens=[]
for alien_number in range(0,30):
new_alien={'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
8.字典中存储列表:
pizza={
'crust':'thick',
'toppings':['mushrooms','extra cheese'],
}
print("you ordered a "+pizza['crust']+'-crust pizza'+
'with the following toppings:')
for topping in pizza['toppings']:
print(topping)
9.字典中存字典:
user={
'cql':{'age':18,'location':'us'},
'ldl':{'age':19,'location':'uk'},
}