python 中的字典

1---字典的创建

        (1){ }---创建空字典

        (2)dict(zip())---通过映射函数创建字典

tt2=["hello","python","byte"]
tt3=["12",'22',"29"]

tt4=dict(zip(tt2,tt3))

print(tt4)

###{'hello': '12', 'python': '22', 'byte': '29'}
###相当于tt2是键 tt3是值

        (3)

ts = dict(ji ="激活卡", ok = '网')
###注意:这个键不能是数字
print(ts)
###{'ji': '激活卡', 'ok': '网'}

(4)创建值为空的字典

name_list=["hello","python"]
keyss=dict.fromkeys(name_list)

### fromkeys()创建值为空的字典

print(keyss)
###{'hello': None, 'python': None}

(5)一个元组一个列表组成字典

tt2 = ("hello", "python", "byte")
tt3 = ["12", '22', "29"]

print({tt2:tt3})

###一个列表一个元组组成字典用{tt2:tt3}

###  {('hello', 'python', 'byte'): ['12', '22', '29']}

2---删除

        (1)del

tt2 = ("hello", "python", "byte")
tt3 = ["12", '22', "29"]
tt4 = dict(zip(tt2, tt3))

del tt4["byte"]
###删除   删除字典中的指定元素的键

print(tt4)
###{'hello': 'world', 'python': '22'}

        (2) clear()---清除字典中的所有元素

3---访问字典键的值

        (1) get()     ()里面的是键

tt2 = ("hello", "python", "byte")
tt3 = ["12", '22', "29"]


tt4 = dict(zip(tt2, tt3))

tt4=tt4.get("python")

print(tt4)

###  22

        (2)[ ]     [ " "]里面是键

tt2 = ("hello", "python", "byte")
tt3 = ["12", '22', "29"]

tt4 = dict(zip(tt2, tt3))

tt5=tt4["hello"]

print(tt5)
###  12

4--遍历字典 

items()--获取字典中的键值对

keys()--获取字典中的键

values()--获取字典中的值

tt2 = ("hello", "python", "byte")
tt3 = ["12", '22', "29"]

tt4 = dict(zip(tt2, tt3))

for item in tt4.items():
###通过 items() 获取键值对
    print(item)
### ('hello', '12')
### ('python', '22')
### ('byte', '29')

for key,value in tt4.items():
    print(key,value)
### hello 12
### python 22
### byte 29

5--添加、修改字典元素

tt2 = ("hello", "python", "byte")
tt3 = ["12", '22', "29"]

tt4['hello']='world'
###修改
###{'hello': 'world', 'python': '22', 'byte': '29'}

tt4['ooo']='title'  
###添加
### {'hello': 'world', 'python': '22', 'byte': '29', 'ooo': 'title'}
print(tt4)

6---字典推导式

tt2 = ("hello", "python")
tt3 = ["12", '22', "29"]
tt4 = dict(zip(tt2, tt3))

tt5={i:random.randint(10,100) for i in range(1,5)}
### i相当于键  
print(tt5)
###  {1: 74, 2: 34, 3: 21, 4: 79}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值