day06_07 字典操作02

1.0 删_del

dic5 = {'age':18,'name':'alex','hobby':'girl'}
del dic5['name'] #删除键值对
print(dic5)
#>>>{'age': 18, 'hobby': 'girl'}

1.1 删_clear

dic5 = {'age':18,'name':'alex','hobby':'girl'}
dic5.clear() #删除了字典的键值对,但是dic5这个字典还是存在的
print(dic5)
#>>>{}

1.1 删_pop (有返回值)

dic5 = {'age':18,'name':'alex','hobby':'girl'}
ret = (dic5.pop('age'))
print (ret)
#>>>18
print(dic5)
#>>>{'hobby': 'girl', 'name': 'alex'}

1.2 删_popitem(随机删除,没啥用)

dic5 = {'age':18,'name':'alex','hobby':'girl'}
a = dic5.popitem() #随机删除,没啥用
#>>>('name', 'alex')
#>>>('hobby', 'girl')
print(a,dic5)
#>>>{'hobby': 'girl', 'age': 18}
#>>>{'name': 'alex', 'age': 18}

 

2.0 其他操作以及涉及到的方法

dic6 = dict.fromkeys(['host1','host2','host3'],'test')
print(dic6)
#>>>{'host1': 'test', 'host3': 'test', 'host2': 'test'}

  

dic6 = dict.fromkeys(['host1','host2','host3'],'test')
print(dic6)
#>>>{'host1': 'test', 'host3': 'test', 'host2': 'test'}

dic6['host2'] = 'abc'
print(dic6)
#>>>{'host2': 'abc', 'host3': 'test', 'host1': 'test'}

dic6 = dict.fromkeys(['host1','host2','host3'],['test1','test2'])
print(dic6)
#>>>{'host3': ['test1', 'test2'], 'host1': ['test1', 'test2'], 'host2': ['test1', 'test2']}

  

2.1 特殊情况

dic6['host2'][1] = 'test'
print(dic6)
#>>>{'host3': ['test1', 'test'], 'host1': ['test1', 'test'], 'host2': ['test1', 'test']}

 

2.2 修改案例(字典嵌套)

av_catalog = {
    "欧美":{
        "www.youporn.com": ["很多免费的,世界最大的","质量一般"],
        "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],
        "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],
        "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
    },
    "日韩":{
        "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
    },
    "大陆":{
        "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
    }
}

av_catalog["大陆"]["1024"][1] += ",可以用爬虫爬下来" #修改
print(av_catalog["大陆"]["1024"])
#>>>['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']

2.3 字典排序

dic = {5:'555',2:'666',4:'444'}
print(sorted(dic))
#>>>[2, 4, 5]
print(sorted(dic.values()))
#>>>['222', '444', '555']
print(sorted(dic.items())) #默认按键排序
#>>>[(2, '666'), (4, '444'), (5, '555')]

  

dic5 = {'name':'alex','age':37}
for i in dic5: #推荐用这种方法,因为效率高
    #print (i) #>>> name age
    print (i,dic5[i])
    #>>>age 37
    #>>>name alex
for i,v in dic5.items(): #方法二
    print(i,v)
    #>>>name alex
    #>>>age 37

  

posted on 2017-09-09 18:36  darkalex001  阅读(156)  评论(0编辑  收藏  举报

导航