一、映射:通过任意键查找集合中值信息的过程,python中通过字典实现映射。字典是键值对的集合。
passwd={"China":"BigCountry","Korean":"SmallCountry","France":"MediumCountry"}
print passwd
运行结果:
{"China":"BigCountry","Korean":"SmallCountry","France":"MediumCountry"}
二、字典的基本操作:
(1)为字典增加一项
dictionaryName[key]=value
(2)删除字典中的一项
del dictionaryName[key]
(3)字典的遍历
for key in students:
print(key+":"+str(students[key]))
(4)遍历字典的键key
for key in dictionaryName.keys():
print(key)
(5)遍历字典的值value
for value in dictionaryName.values():
print(value)
(6)遍历字典的项
passwd={"China":"BigCountry","Korean":"SmallCountry","France":"MediumCountry"}
for item in passwd.items():
print(item)
运行结果:
('China', 'BigCountry')
('Korean', 'SmallCountry')
('France', 'MediumCountry')
(7)遍历字典的key-value
passwd={"China":"BigCountry","Korean":"SmallCountry","France":"MediumCountry"}
for item,value in passwd.items():
print(item,value)
运行结果:
China BigCountry
Korean SmallCountry
France MediumCountry
(8)判断一个键是否在字典中in或not in
>>>passwd={"China":"BigCountry","Korean":"SmallCountry","France":"MediumCountry"}
>>>"China" in passwd
True
>>>"America" in passwd
False
(9)clear()删除字典中的所有项目
get(key)返回字典中key对应的值
pop(key)删除并返回字典中key对应的值
update(字典)将字典中的键值添加到字典中
>>>passwd={"China":"BigCountry","Korean":"SmallCountry","France":"MediumCountry"}
>>>passwd.get("China")
"BigCountry"
>>>passwd.pop(Korean)
"SmallCountry"
>>>passwd
{"China":"BigCountry","France":"MediumCountry"}
>>>passwd.clear()
>>>passwd
{}