字典类型

一、映射:通过任意键查找集合中值信息的过程,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
{}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值