day2-字典

news/2024/7/19 11:53:39 标签: 爬虫

一 概述

字典是一种key - value 的数据类型,使用就像我们上学用的字典,通过笔画,字母来查对应页的详细内容。

字典的特性:

  • dict是无序的
  • key必须是唯一的

二 语法

语法

info = {
    'stu1601': 'gangtiexia',
    'stu1602': 'zhizhuxia',
    'stu1603': 'jianbingxia'
}

三 基本用法

1.增加

>>> info = {
...     'stu1601': 'gangtiexia',
...     'stu1602': 'zhizhuxia',
...     'stu1603': 'jianbingxia'
... }
>>> info
{'stu1601': 'gangtiexia', 'stu1602': 'zhizhuxia', 'stu1603': 'jianbingxia'}
>>> info['stu1605'] = '绿巨人'
>>> info
{'stu1601': 'gangtiexia', 'stu1602': 'zhizhuxia', 'stu1603': 'jianbingxia', 'stu1605': '绿巨人'}

2. 修改

>>> info
{'stu1601': 'gangtiexia', 'stu1602': 'zhizhuxia', 'stu1603': 'jianbingxia', 'stu1605': '绿巨人'}
>>> info['stu1601'] = '钢铁侠'
>>> info
{'stu1601': '钢铁侠', 'stu1602': 'zhizhuxia', 'stu1603': 'jianbingxia', 'stu1605': '绿巨人'}

3. 删除(del pop popitem)

>>> info
{'stu1601': '钢铁侠', 'stu1602': 'zhizhuxia', 'stu1603': 'jianbingxia', 'stu1605': '绿巨人'}
>>> info.pop('stu1601') #标准删除姿势
'钢铁侠'
>>> info
{'stu1602': 'zhizhuxia', 'stu1603': 'jianbingxia', 'stu1605': '绿巨人'}
>>> del info['stu1602']  #换个删除姿势
>>> info
{'stu1603': 'jianbingxia', 'stu1605': '绿巨人'}
>>> info.popitem()  #随机删除
('stu1605', '绿巨人')
>>> info
{'stu1603': 'jianbingxia'}

4. 查找

>>> info
{'stu1601': 'gangtiexia', 'stu1602': 'zhizhuxia', 'stu1603': 'jianbingxia'}
>>> 'stu1601' in info #标准用法
True
>>> info.get('stu1602')  #获取
'zhizhuxia'
>>> info['stu1603']  #同上,但是看下面
'jianbingxia'
>>> info['stu1604']  #如果一个key不存在,报错,get不会,不存在只返回None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'stu1604'

5.多级字典嵌套及操作

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"])
#ouput 
['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']

四 其他用法

1. values()

以列表返回一个字典所有的值

>>> info
{'stu1601': 'gangtiexia', 'stu1602': 'zhizhuxia', 'stu1603': 'jianbingxia'}
>>> info.values()
dict_values(['gangtiexia', 'zhizhuxia', 'jianbingxia'])

2. keys()

以列表返回一个字典所有的键

>>> info
{'stu1601': 'gangtiexia', 'stu1602': 'zhizhuxia', 'stu1603': 'jianbingxia'}
>>> info.keys()
dict_keys(['stu1601', 'stu1602', 'stu1603'])

3. setdefault(key, default=None)

如果键不存在于字典中,将会添加键,并将值设为默认值;如果字典中包含给定的键,则返回该键对应的值

>>> info
{'stu1601': 'gangtiexia', 'stu1602': 'zhizhuxia', 'stu1603': 'jianbingxia'}
>>> info.setdefault('stu1601','钢铁侠') #存在的key
'gangtiexia'
>>> info
{'stu1601': 'gangtiexia', 'stu1602': 'zhizhuxia', 'stu1603': 'jianbingxia'}
>>> info.setdefault('stu1604','钢铁侠') #不存在的key
'钢铁侠'
>>> info
{'stu1601': 'gangtiexia', 'stu1602': 'zhizhuxia', 'stu1603': 'jianbingxia', 'stu1604': '钢铁侠'}

4.dict.update(dict2) 

把字典dict2的键值对更新到dict里,合并两个字典

>>> info
{'stu1601': 'gangtiexia', 'stu1602': 'zhizhuxia', 'stu1603': 'jianbingxia', 'stu1604': '钢铁侠'}
>>> b = {'stu1602':'蜘蛛侠','1':'2',3:4}
>>> info.update(b) #把字典b的键值对更新到info里
>>> info
{'stu1601': 'gangtiexia', 'stu1602': '蜘蛛侠', 'stu1603': 'jianbingxia', 'stu1604': '钢铁侠', '1': '2', 3: 4}

5. items()

以列表返回可遍历的(键,值)元组数组

>>> info
{'stu1601': 'gangtiexia', 'stu1602': '蜘蛛侠', 'stu1603': 'jianbingxia', 'stu1604': '钢铁侠', '1': '2', 3: 4}
>>> info.items()
dict_items([('stu1601', 'gangtiexia'), ('stu1602', '蜘蛛侠'), ('stu1603', 'jianbingxia'), ('stu1604', '钢铁侠'), ('1', '2'), (3, 4)])

6. fromkeys(序列,默认值)

初始化一个字典

>>> dict.fromkeys(['a','b'],1)
{'a': 1, 'b': 1}

7. clear()

清空字典

>>> info
{'stu1601': 'gangtiexia', 'stu1602': '蜘蛛侠', 'stu1603': 'jianbingxia', 'stu1604': '钢铁侠', '1': '2', 3: 4}
>>> info.clear()
>>> info
{}

5. 循环dict

#方法1
for key in info:
    print(key,info[key])

#方法2
for k,v in info.items(): #会先把dict转成list,数据量大时莫用
    print(k,v)

小结:

  1. 方法1的效率比方法2的效率高很多
  2. 方法1是直接通过key取value
  3. 方法2是先把字典转换成一个列表,再去取值
  4. 当数据量比较大的时候,用第二种方法时,字典转换成列表的这个过程需要花大量的时间老转换,当然数据量不大,没有关系,效率差不多

6. 知识扩展

1. 合并两个字典的多种方法

>>> dic1 = {'a':1,"b": 2}
>>> dic2 = {'c':3,"d": 4}

# 方法一
>>> res = {}
>>> res.update(dic1)
>>> res.update(dic2)
>>> res
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

#方法二
>>> def update(dic1,dic2):
...     for key, value in dic2.items():
...         dic1[key] = value
... 
>>> update(dic1,dic2)
>>> dic1
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

#方法三
>>> dic1 = {'a':1,"b": 2}
>>> dic2 = {'c':3,"d": 4}
>>> res3 = dict(dic1, **dic2)
>>> res3
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

#方法四
>>> dic1 = {'a':1,"b": 2}
>>> dic2 = {'c':3,"d": 4}
>>> res4 = {**dic1, **dic2}
>>> res4
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

 

转载于:https://www.cnblogs.com/Easonlou/p/8136641.html


http://www.niftyadmin.cn/n/1823608.html

相关文章

Excel打开csv文件乱码问题的解决办法

excel打开csv 出现乱码怎么解决 https://jingyan.baidu.com/article/ac6a9a5e4c681b2b653eacf1.html CSV是逗号分隔值的英文缩写&#xff0c;通常都是纯文本文件。CSV格式是分隔的数据格式&#xff0c;有字段/列分隔的逗号字符和记录/行分隔换行符。通常CSV文件可以用EXCEL正常…

【RFC3027-IP NAT的协议复杂性】第一篇(缩译)

原文&#xff1a;rfc3027 (ietf.org) Protocol Complications with the IP Network Address Translator IP网络地址转换器的协议复杂性 注&#xff1a;内容较多&#xff0c;翻译从目录开始&#xff1b;缩减部分会在其后进行备注说明【有缩减】 目录 1.0 介绍 2.0 NAT破坏协…

CSS-实现倒影效果box-reflect

我需要的效果&#xff1a; html: <img src"images/my1.jpg" width"20%"/> css: img{-webkit-box-reflect: below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), to(rgba(250, 250, 250, 0.1)));} 浏览器的兼容性box-re…

Codeforces Round #455 (Div. 2) 909D. Colorful Points

题 OvO http://codeforces.com/contest/909/problem/D CF 455 div2 D CF 909D 解 算出模拟的复杂度之后就是一个很水的模拟题 把字符串按照类似于行程编码的方式来表示&#xff0c;例如把 aaaabbccc 表示成 [4*a] [2*b] [3*c] 这样的形式&#xff08;[4*a] 这个用一个结构体表示…

NETAPP E-Series 使用简单配置

1.安装步骤&#xff1a; SANtricityStorage Management软件的安装。 1) 进入安装页面后&#xff0c;会出现安装目录选择页面&#xff0c;根据您的实际需要选择安装目录点击“Next”&#xff0c;选择安装目录&#xff1a; 2) 根据用户的环境配置选择安装方式。单击“Next”进入下…

查询区间内距离标尺最近且不大于最大值的元素

一个混杂数组中&#xff0c;要求找到指定标尺相差最小的元素并且该元素不得超出规定的最大值&#xff0c;如何查找呢&#xff1f; 比如 在数组 array(1,2,34,5,6,7,10,31,40,32,36,58,83,4,3) 中&#xff0c;要求找到距离20最近但是又不得大于30的元素 那么这道题很明显&#…

使用angular4和asp.net core 2 web api做个练习项目(一)

这是一篇学习笔记. angular 5 正式版都快出了, 不过主要是性能升级. 我认为angular 4还是很适合企业的, 就像.net一样. 我用的是windows 10 安装工具: git for windows: 官网很慢, 所以找一个镜像站下载: https://github.com/waylau/git-for-win, 淘宝镜像的速度还是蛮快的: 安…

.22-浅析webpack源码之事件流compilation总览

呃&#xff0c;终于到了这地方…… newCompilation(params) {// ...this.applyPlugins("this-compilation", compilation, params);// 31console.log(this._plugins[compilation].length);this.applyPlugins("compilation", compilation, params);return c…