第十六节,基本数据类型,字典dict
字典
常用操作:
索引
新增
删除
键、值、键值对
循环
长度
字典由键值对组成,由一个键(名称)和 一个值组成,与列表和元组不同的是里面的元素是有键的(名称)
所以当要打印字典时,打印字典变量加[键]即可
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
print(a["ls"])
#打印出 2 打印出了ls键的值
创建字典
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {"zhs":"", "ls":"", "ww":""}
#或者
a = dict({"zhs":"", "ls":"", "ww":""})
#或者
a = {
"zhs":"",
"ls":"",
"ww":""
}
#一般采用第三中,更容易读
索引
打印字典变量加[要打印的键]
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
print(a["ls"])
print(a["ww"])
#打印出 2 3 打印出了ls和ww键的值
for循环
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
for b in a:
print(b)
#打印出 ww zhs ls 默认循环出的是字典的键 a = {
"zhs":"",
"ls":"",
"ww":""
}
for b in a:
print(a[b])
#打印出 3 1 2 要打印字典变量加上[自定义循环变量,也就是键]才能打印出值
keys(self)
"""(获取字典的键)""":返回一个字典的键列表
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
print(a.keys())
#打印出 ['ww', 'zhs', 'ls'] 返回字典键列表
values(self)
"""(获取字典的值)""":返回一个字典的值列表
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
print(a.values())
#打印出 ['3', '1', '2'] 返回字典值列表
items(self)
"""(获取字典里的键和值)""":返回一个字典的键和值列表加元组
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
print(a.items())
#打印出 [('ww', '3'), ('zhs', '1'), ('ls', '2')] 返回字典里的键和值列表加元组
(keys:获取键) (values:获取值) (items:获取键和值) 结合for循环
(keys:获取键)结合for循环
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
for b in a.keys():
print(b)
#打印出 ww zhs ls 循环出了字典的键
(values:获取值)结合for循环
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
for b in a.values():
print(b)
#打印出 3 1 2 循环出了字典的值
(items:获取键和值)结合for循环
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
for k, v in a.items(): #因为items()获取的键和值,所以循环里要自定义两个变量分别代表键和值
print(k)
print(v)
#打印出 ww 3 zhs 1 ls 2 循环出了字典的键和值
clear(self)
"""(清除字典里的所有内容)"""
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
a.clear()
print(a)
#打印出 {} 字典里是空的
get(self, k, d=None)(推荐使用)
""" (根据key(键)获取值,如果key(键)不存在可以指定默认值 )""":如果键后面指定了默认值,键存在就获取键自身的值,如果键不存在就获取默认值
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
print(a.get("ls"))
#打印出 2 输出指定键的值 a = {
"zhs":"",
"ls":"",
"ww":""
}
print(a.get("xyz","")) #xyz键不存在,就获取默认值123
#打印出 123 输出指定键的值,如果指定键不存在就输出默认值
has_key(self, k)
注意:python3版本以上已经取消了
""" (:键)key:键,名称 """:返回真或者假
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
print(a.has_key("ls"))
#打印出 True 返回真说明字典里有ls这个键
判断字典里是否有某个key键:返回真或者假
也可以判断字典里是否有某个值
注意:python3版本以上使用这个方法替代已经取消的has_key
格式:"要判断的键" in 字典变量.keys()
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
b = "ls" in a.keys()
print(b)
#打印出 True 返回真说明字典里有ls这个键 a = {
"zhs":"",
"ls":"",
"ww":""
}
b = "" in a.values()
print(b)
#打印出 True 返回真说明字典里有2这个值
update(self, E=None, **F)
""" (追加更新)"""要追加更新的变量
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
b = {
"z":"",
"l":"",
"w":""
}
a.update(b)
print(a)
#打印输出 {'ww': '3', 'zhs': '1', 'ls': '2', 'w': '6', 'z': '4', 'l': '5'} 将b字典追加更新到了a字典
追加更新 2
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#这个方法是。如果字典里存在k4这个键就987的值更新给k4键,如果不存在k4键就在字典里创建k4键值为987
a = {
"k1":123,
"k2":456,
"k3":789,
}
a["k4"] = 987
print(a)
删除字典里的元素
格式:del 字典变量.[要删除的元素键]
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = {
"zhs":"",
"ls":"",
"ww":""
}
del a["ls"]
print(a)
#打印输出 {'ww': '3', 'zhs': '1'} 删除了ls键这个元素
fromkeys(*args, **kwargs)
"""(查找字典里一个或多个元素的键,将查找的键重新指定新的值)要查找的元素键,要改变的新值"""
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#fromkeys 查找字典里一个或多个元素的键,将查找的键重新指定新的值
a = {"k1":123, "k2":456, "k3":789}
b = a.fromkeys(["k1", "k2", "k3"], "")
print(b)
#输出 {'k2': '876', 'k3': '876', 'k1': '876'}
class dict(object):
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
""" def clear(self): # real signature unknown; restored from __doc__
""" 清除内容 """
""" D.clear() -> None. Remove all items from D. """
pass def copy(self): # real signature unknown; restored from __doc__
""" 浅拷贝 """
""" D.copy() -> a shallow copy of D """
pass @staticmethod # known case
def fromkeys(S, v=None): # real signature unknown; restored from __doc__
"""
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.
"""
pass def get(self, k, d=None): # real signature unknown; restored from __doc__
""" 根据key获取值,d是默认值 """
""" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
pass def has_key(self, k): # real signature unknown; restored from __doc__
""" 是否有key """
""" D.has_key(k) -> True if D has a key k, else False """
return False def items(self): # real signature unknown; restored from __doc__
""" 所有项的列表形式 """
""" D.items() -> list of D's (key, value) pairs, as 2-tuples """
return [] def iteritems(self): # real signature unknown; restored from __doc__
""" 项可迭代 """
""" D.iteritems() -> an iterator over the (key, value) items of D """
pass def iterkeys(self): # real signature unknown; restored from __doc__
""" key可迭代 """
""" D.iterkeys() -> an iterator over the keys of D """
pass def itervalues(self): # real signature unknown; restored from __doc__
""" value可迭代 """
""" D.itervalues() -> an iterator over the values of D """
pass def keys(self): # real signature unknown; restored from __doc__
""" 所有的key列表 """
""" D.keys() -> list of D's keys """
return [] def pop(self, k, d=None): # real signature unknown; restored from __doc__
""" 获取并在字典中移除 """
"""
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
"""
pass def popitem(self): # real signature unknown; restored from __doc__
""" 获取并在字典中移除 """
"""
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
"""
pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
""" 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """
""" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
pass def update(self, E=None, **F): # known special case of dict.update
""" 更新
{'name':'alex', 'age': 18000}
[('name','sbsbsb'),]
"""
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
"""
pass def values(self): # real signature unknown; restored from __doc__
""" 所有的值 """
""" D.values() -> list of D's values """
return [] def viewitems(self): # real signature unknown; restored from __doc__
""" 所有项,只是将内容保存至view对象中 """
""" D.viewitems() -> a set-like object providing a view on D's items """
pass def viewkeys(self): # real signature unknown; restored from __doc__
""" D.viewkeys() -> a set-like object providing a view on D's keys """
pass def viewvalues(self): # real signature unknown; restored from __doc__
""" D.viewvalues() -> an object providing a view on D's values """
pass def __cmp__(self, y): # real signature unknown; restored from __doc__
""" x.__cmp__(y) <==> cmp(x,y) """
pass def __contains__(self, k): # real signature unknown; restored from __doc__
""" D.__contains__(k) -> True if D has a key k, else False """
return False def __delitem__(self, y): # real signature unknown; restored from __doc__
""" x.__delitem__(y) <==> del x[y] """
pass def __eq__(self, y): # real signature unknown; restored from __doc__
""" x.__eq__(y) <==> x==y """
pass def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
# (copied from class doc)
"""
pass def __iter__(self): # real signature unknown; restored from __doc__
""" x.__iter__() <==> iter(x) """
pass def __len__(self): # real signature unknown; restored from __doc__
""" x.__len__() <==> len(x) """
pass def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass @staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__
""" x.__setitem__(i, y) <==> x[i]=y """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" D.__sizeof__() -> size of D in memory, in bytes """
pass __hash__ = None
dict
字典的功能
索引
增加
删除
for循环
长度
项
键
值
判断是否存在某元素
更新
第十六节,基本数据类型,字典dict的更多相关文章
- 第三百四十六节,Python分布式爬虫打造搜索引擎Scrapy精讲—Requests请求和Response响应介绍
第三百四十六节,Python分布式爬虫打造搜索引擎Scrapy精讲—Requests请求和Response响应介绍 Requests请求 Requests请求就是我们在爬虫文件写的Requests() ...
- ASP.NET MVC深入浅出系列(持续更新) ORM系列之Entity FrameWork详解(持续更新) 第十六节:语法总结(3)(C#6.0和C#7.0新语法) 第三节:深度剖析各类数据结构(Array、List、Queue、Stack)及线程安全问题和yeild关键字 各种通讯连接方式 设计模式篇 第十二节: 总结Quartz.Net几种部署模式(IIS、Exe、服务部署【借
ASP.NET MVC深入浅出系列(持续更新) 一. ASP.NET体系 从事.Net开发以来,最先接触的Web开发框架是Asp.Net WebForm,该框架高度封装,为了隐藏Http的无状态模 ...
- 大白话5分钟带你走进人工智能-第二十六节决策树系列之Cart回归树及其参数(5)
第二十六节决策树系列之Cart回归树及其参数(5) 上一节我们讲了不同的决策树对应的计算纯度的计算方法, ...
- 第一百二十六节,JavaScript,XPath操作xml节点
第一百二十六节,JavaScript,XPath操作xml节点 学习要点: 1.IE中的XPath 2.W3C中的XPath 3.XPath跨浏览器兼容 XPath是一种节点查找手段,对比之前使用标准 ...
- 第十六节、基于ORB的特征检测和特征匹配
之前我们已经介绍了SIFT算法,以及SURF算法,但是由于计算速度较慢的原因.人们提出了使用ORB来替代SIFT和SURF.与前两者相比,ORB有更快的速度.ORB在2011年才首次发布.在前面小节中 ...
- 第四百一十六节,Tensorflow简介与安装
第四百一十六节,Tensorflow简介与安装 TensorFlow是什么 Tensorflow是一个Google开发的第二代机器学习系统,克服了第一代系统DistBelief仅能开发神经网络算法.难 ...
- 第三百八十六节,Django+Xadmin打造上线标准的在线教育平台—HTML母版继承
第三百八十六节,Django+Xadmin打造上线标准的在线教育平台—HTML母版继承 母板-子板-母板继承 母板继承就是访问的页面继承一个母板,将访问页面的内容引入到母板里指定的地方,组合成一个新页 ...
- 第三百七十六节,Django+Xadmin打造上线标准的在线教育平台—创建用户操作app,在models.py文件生成5张表,用户咨询表、课程评论表、用户收藏表、用户消息表、用户学习表
第三百七十六节,Django+Xadmin打造上线标准的在线教育平台—创建用户操作app,在models.py文件生成5张表,用户咨询表.课程评论表.用户收藏表.用户消息表.用户学习表 创建名称为ap ...
- 第三百六十六节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)的bool组合查询
第三百六十六节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)的bool组合查询 bool查询说明 filter:[],字段的过滤,不参与打分must:[] ...
- 第三百五十六节,Python分布式爬虫打造搜索引擎Scrapy精讲—scrapy分布式爬虫要点
第三百五十六节,Python分布式爬虫打造搜索引擎Scrapy精讲—scrapy分布式爬虫要点 1.分布式爬虫原理 2.分布式爬虫优点 3.分布式爬虫需要解决的问题
随机推荐
- win10 Qt 调试器未设置
安装win10后一直用vs调试,没有用qt调试,这次启动调试,发现提示调试器未设置. 解决办法: 需要重新安装wdk 10 https://developer.microsoft.com/zh-cn/ ...
- Spark Streaming的wordcount案例
之前测试的一些spark案例都是采用离线处理,spark streaming的流处理一样可以运行经典的wordcount. 基本环境: spark-2.0.0 scala-2.11.0 IDEA-15 ...
- 二十九、oracle 触发器
一.触发器简介 触发器的定义就是说某个条件成立的时候,触发器里面所定义的语句就会被自动的执行.因此触发器不需要人为的去调用,也不能调用.然后,触发器的触发条件其实在你定义的时候就已经设定好了.这里面需 ...
- mui 访问手机自带是否连接网络
//mui检测是否连接网络 function getSysInfo() { // var str = ""; // str += "名称:" + plus. ...
- fzu Problem 2128 最长子串(KMP + strstr 经典好题)
Problem Description 问题很简单,给你一个字符串s,问s的子串中不包含s1,s2...sn的最长串有多长. Input 输入包含多组数据.第一行为字符串s,字符串s的长度1到10 ...
- VS2013使用EF与mysql数据库.
一个VS2013的mvc+EF+mysql的项目,需要连接Mysql数据库 一,下载一个mysql-for-visualstudio-1.2.3.msi,在自己的电脑上安装,这个是解决在创建实体模型( ...
- HDU 4247 A Famous ICPC Team
Problem Description Mr. B, Mr. G, Mr. M and their coach Professor S are planning their way to Warsaw ...
- JS复习:第二十二章
一.高级函数 1.在任何值上调用Object原声的toString( )方法,都会返回一个[object NativeConstructorName]格式d字符串.每个类在内部都有一个[[Class] ...
- POJ 1678 I Love this Game!#dp博弈
http://poj.org/problem?id=1678 #include<iostream> #include<cstdio> #include<cstring&g ...
- Java 泛型 协变式覆盖和泛型重载
Java 泛型 协变式覆盖和泛型重载 @author ixenos 1.协变式覆盖(Override) 在JDK 1.4及以前,子类方法如果要覆盖超类的某个方法,必须具有完全相同的方法签名,包括返回值 ...