码迷,mamicode.com
首页 > 编程语言 > 详细

Python3-笔记-B-002-数据结构-字典dict{ }

时间:2017-10-25 18:04:15      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:ems   span   none   获取   不能   val   soft   字典   数字   


def dics():
# --- 字典 ----
# 创建(由 键值对(key:value) 组成)
dics = {1: "a", 2: "b", 3: "c"}
dics = dict() # 创建空字典
dics = dict([(1, "a"), (2, "b")]) # (序列)转为字典 (列表序列: dict([[1, "a"], [2, "b"]]); 元组列表: dict(((1, "a"), (2, "b"))))
dics = dict(a=1, b=2) # (: 格式固定, 字母 = 数字, 字母不能加") # => {‘a‘: 1, ‘b‘: 2}
dics = {chr(x): x for x in range(65, 80)}

# 获取
dics = {1: "a", 2: "b", 3: "c"}
strs = dics[1] # keyvalue, 没有对应key时抛异常(注意)
strs = dics.get(1) # key获取value
strs = dics.get(5, -1) # -1 为没有该key的返回
strs = dics.setdefault(50) # keyvalue, key不存在则添加,valueNone
strs = dics.setdefault(12, -1) # -1为不存在key,添加的value-1 {1: ‘a‘, 2: ‘b‘, 3: ‘c‘, 50: None, 12: -1}
keys = dics.keys() # 所有key, dict_keys([1, 2, 3, 50, 12])
values = dics.values() # 所有value, dict_values([‘a‘, ‘b‘, ‘c‘, None, -1])
kevaList = dics.items() # 获取(key,value)列表,格式为[(key1, value1), (key2, value2)], dict_items([(1, ‘a‘), (2, ‘b‘), (3, ‘c‘), (50, None), (12, -1)])
dics2 = dics.copy() # 浅拷贝
dics3 = dics.fromkeys(dics) # 根据字典所有key创建新字典,valueNone, {1: None, 2: None, 3: None, 50: None, 12: None}
dics4 = dics.fromkeys(dics, -1) # -1为创建的新字典,value-1, {1: -1, 2: -1, 3: -1, 50: -1, 12: -1}

# 查找
key = min(dics) # 最小键
key = max(dics) # 最大键
# 添加
dics.update({4: "d", 5: "f"}) # 添加字典 {1: ‘a‘, 2: ‘b‘, 3: ‘c‘, 50: None, 12: -1, 4: ‘d‘, 5: ‘f‘}


# 修改
dics[1] = "c" # {1: ‘c‘, 2: ‘b‘, 3: ‘c‘, 50: None, 12: -1, 4: ‘d‘, 5: ‘f‘}

# 删除
del dics[1] # 删除 键1 (注意)
dics4.clear() # 清空
strs = dics.pop(3) # 删除,返回被删的元素(注意:key同时删)
strs = dics.pop(5, -1) # -1 为没有该key时的返回
pul = dics.popitem() # 删除键值对,返回被删的元组(末尾起删)

# 统计
length = len(dics) # 字典长度

# 判断
boolean = 1 in dics # key是否在字典中存在
boolean = 1 not in dics # key是否不在字典中存在


# 遍历
for key, value in dics.items():   
  print("key:%d value:%s" % (key, value))

# 排序
lists = sorted(dics) # :返回排序后的键列表

Python3-笔记-B-002-数据结构-字典dict{ }

标签:ems   span   none   获取   不能   val   soft   字典   数字   

原文地址:http://www.cnblogs.com/vito13/p/7729951.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!