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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python3-笔记-B-002-数据结构-字典dict{ }相关的知识,希望对你有一定的参考价值。


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{ }的主要内容,如果未能解决你的问题,请参考以下文章

python3.x学习笔记2018-02-02更新

Python3学习笔记-字典(dict)

Python3学习笔记--数据类型:字符串列表元组数字字典集合

Python3.5学习笔记-列表元组字典

Python3-笔记-E-008-库-字典序列化shelve

Python3 字典