您的位置:首页 > 其它

映射类型:字典

2018-01-02 14:58 113 查看
字典:如果想将值分组到一个结构中,并且通过编号对其进行引用,列表就能派上用场了。字典是一种通过名字引用值的数据结构,字典中的值并没有特殊的顺序,但是都是存储在一个特定的键(Key)里,键可以是数字、字符串或者元组。

1.如何创建字典和给字典赋值

创建字典只需要把字典赋值给一个变量,不管这个字典是否包含元素。

赋值创建字典 , key-value , 键值对
d = {"key1":"value1", "key2":"value2"}
print d
{'key2': 'value2', 'key1': 'value1'}

services = {"ssh":22, "ftp":[20,21], "http":[80, 8080]}
print services
{'ftp': [20, 21], 'http': [80, 8080], 'ssh': 22}


2.分析字典的特性(跟元组和列表比较)

字典不能索引和切片,因为字典是无序的数据类型;

字典不支持重复和连接;

字典支持成员操作符: 判断字典的key值是否在字典中存在; in, not in

3.字典的增删改查

1)增

字典名[key] = value

d.update(a=1, b=2)

d.update({‘a’:1, ‘b’,2})

d.setdefault(‘a’, 1)

** 重点: setdefault 和 update方法的不同

services = {"ftp":[20,21]}
# 通过字典名 [key]=value, 将 key-value 添加到字典中 ;
services['http'] = [80, 8080]
print services
{'ftp': [20, 21], 'http': [80, 8080]}




# update 方法实现添加: key 存在,覆盖 value 值, 否则,添加
services = {"ftp":[20,21]}
services1 = {'http':[80,8080]}
# services.update(services1)
# print services
# 更建议使用
services.update(http=[80,8080], ftp=22)
print services
{'ftp': 22, 'http': [80, 8080]}




# setdefault 实现添加: key 存在,不覆盖 value 值, 否则,添加
services = {"ftp":[20,21]}
services1 = {'http':[80,8080]}
services.setdefault("ftp", 22)
print services
{'ftp': [20, 21]}




2)改

字典名[key]=value
d.update({'a':2, 'b':3})
d.update(a=2, b=3)






3)查

查看key值;

查看value值;

查看key-value键值对;

查看key是否存在;

services = {'ftp': 22, 'http': [80, 8080]}
# 查看 key 值
services.keys()
services.viewkeys()
services.iterkeys()
# 给 key 起名字

# 查看 value 值
services.values()

# 查看 key-value 键值对
services.items()

# 查看 key 是否存在 ;
services.has_key('ftpp')
# 查看指定 key 对应的 value 值;如果 key 不存在,不报错; 如果存在,返回 value 值;
# services['ftp'] 如果 key 不存在,直接报错;
services.get('ftpp')


4)删

d.pop(key)      删除指定 key 的字典元素;
d.popitem()     随机删除字典的 key-value 元素 ;
del d[key]      删除指定 key 的字典元素;
d.clear()       清空字典元素


4.循环遍历字典

for i,j in services.items():
print i,j
ftp 22
http [80, 8080]

# 默认情况下遍历字典的 key 值;
for i in services:
print i
ftp
http


5.字典应用

应用1: 通过字典实现case语句

目前python不支持case语句;

实现case语句的两种方式:

if…elif…elif…else…

字典实现:

# if...elif...elif...else... 实现:
#coding:utf-8
"""
# 实现四则运算
- 用户分别输入第一个数字,运算操作符,第三个数字;
- 根据用户的运算操作打印出运算结果;
"""
from __future__ import division
num1 = input()
ope = raw_input()
num2 = input()


# case 语句
if ope == "+":
print num1+num2
elif ope == "-":
print num1-num2
elif ope == "*":
print num1*num2
elif ope == "/":
print num1/num2
else:
print "error operator"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: