Python自学-内置数据结构(变量类型dict)

字典

  • 字典是一种没有顺序的组合数据,数据以键值对形式出现
# 字典的创建

# 创建空字典1
d = {}
print(type(d))
print(d,"\n")

# 创建空字典2
d1 = dict()
print(type(d1))
print(d1,"\n")

# 创建非空字典1
d3 = {"one":1,"two":2,"three":3}
print(d3)

# 创建非空字典2
d4 = dict(one=1,two=2,three=3)
print(d4)

# 创建非空字典3
d5 = dict([("one",1),("tow",2),("three",3)])
print(d5)
<class 'dict'>
{} 

<class 'dict'>
{} 

{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'tow': 2, 'three': 3}

字典的特性

  • 字典是序列类型,但是是无序序列,所以没有分片和索引
  • 字典中的数据都是键值对,即 key - value
    • key:必须是可哈希的值,如int,str,float,tuple,但list,set,dict不行
    • values:任何值

字典的常见操作

# 访问数据
d = {"one":1,"two":2,"three":3}
# 注意访问格式
# 中括号内是 key,返回的是 values
print(d["one"],"\n")

# 修改指定 key 的 values
d["one"] = "10000"
print(d,"\n")

# del 删除一组键值对
del d["one"]
print(d,"\n")

# 成员检测, in,not in
d = {"one":1,"two":2,"three":3}
# 通过以下代码执行结果判定成员检测依据 key
if 2 in d:
    print("value")
if "two" in d:
    print("key")
if ("two",2) in d:
    print("key-value")

print("\n")

# 遍历在 python2 和 python3 中区别较大,代码不通用
d = {"one":1,"two":2,"three":3}
# 按 key 来使用 for 循环:
for k in d:
    print(k)
print("\n")
# 上述代码可改写为:
for k in d.keys():
    print(k)

print("\n")

# 值访问字典的值
for v in d.values():
    print(v)
    
print("\n")

# 注意以下特殊用法
for k,v in d.items():
    print(k,"--",v)
1 

{'one': '10000', 'two': 2, 'three': 3} 

{'two': 2, 'three': 3} 

key


one
two
three


one
two
three


1
2
3


one -- 1
two -- 2
three -- 3

字典生成式

d = {"one":1,"two":2,"three":3}

# 常规字典生成式
dd = {k:v for k,v in d.items()}
print(dd)

# 加限制条件的字典生成式
ddd = {k:v for k,v in d.items() if v % 2 == 0}
print(ddd)
{'one': 1, 'two': 2, 'three': 3}
{'two': 2}

字典相关函数

# 通用函数:len,max,min,dict
# str(字典):返回字典的字符串格式
d = {"one":1,"two":2,"three":3}
print(str(d),"\n")

# items:返回字典的键值对组成的元组格式,可迭代结构
i = d.items()
print(type(i))
print(i,"\n")

# keys:返回字典的键组成的一个可迭代结构
k = d.keys()
print(type(k))
print(k,"\n")

# values:返回字典的值组成的一个可迭代结构
v = d.values()
print(type(v))
print(v,"\n")

# get:根据指定键返回对应的值,可设置默认值
print(d.get("one"))    # 找到指定键,则返回对应值
print(d.get("two2",666))   # 找不到指定键,则返回默认值
print(d["one"],"\n")    # 指定键在字典内,返回对应值,指定键不在字典内,则报错

# fromkeys:使用指定的序列作为键,使用一个值作为字典的所有的键的值
l = ["eins","zwei","drei"]
# 注意 fromkeys 两个参数的类型
d = dict.fromkeys(l,"hahahahaha")
print(d,"\n")

# clear:清空字典
d.clear()
print(d,"\n")
{'one': 1, 'two': 2, 'three': 3} 

<class 'dict_items'>
dict_items([('one', 1), ('two', 2), ('three', 3)]) 

<class 'dict_keys'>
dict_keys(['one', 'two', 'three']) 

<class 'dict_values'>
dict_values([1, 2, 3]) 

1
666
1 

{'eins': 'hahahahaha', 'zwei': 'hahahahaha', 'drei': 'hahahahaha'} 

{} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值