当前位置: 代码迷 >> 综合 >> Python 字典 dict
  详细解决方案

Python 字典 dict

热度:11   发布时间:2023-12-01 13:06:19.0

字典基础

s=[("zz",1),("zz2",2)]
dic=dict(s);
print(dict(s))  #转字典
print(dict(s)["zz"])
dicAreas={
    }
print(type(dicAreas))
dicAreas["dd"]="dddd"
dicAreas["dd2"]="dddd2"
dicAreas["dd2"]="23333"  #更新print(dicAreas)
del dicAreas['dd']
print(dicAreas)print(dicAreas.pop("dd2"))  #返回删除的对象 的值
print(dicAreas.pop("dd2333","不存在"))  #不存在可设置值 不然报错
dicAreas["222"]=322222
print(dicAreas.popitem())#随机删除
print(dicAreas.clear())  #清空
del dicAreas  #删除字典的对象dicAreas={
    }
dicAreas['ss']='dkjdkld'
print("中国" in dicAreas)
print("ss" in dicAreas)print(dicAreas.get("sss","不存在")) #存在返回值 不存在 返回你设置的默认的值

统计字符串个数

ss="i love youo your youu loce"
dictAreas={}
for i in ss:dictAreas[i]=dictAreas.get(i,0)+1  #get可以默认返回0 找不到就返回0
print(dictAreas)

重点 字典排序

print(dictAreas.items())  #返回双元素 元祖的列表
print(dictAreas.keys())    #键链表
print(dictAreas.values())    #值链表dictAreas={
    "china":9001,"russia":9090}
for k,v in dictAreas.items():print(k,v)
ls=sorted(dictAreas)
for country in ls :print(country,dictAreas[country])#字典排序
lsVK=[(v,k) for k,v in dictAreas.items()]
lsVK.sort()
lsKV=[(k,v) for v,k in lsVK]
print(lsKV)dictAreas=dict(lsKV)
dictAreas2={
    "djkd":333,"china":9000}
dictAreas.update(dictAreas2)   #如果存在就跟新 不存在就自动加入新的元素
print(dictAreas)new=dict(dictAreas,**dictAreas2)  #dict生成一个新的
print(new)