字典由多个键与其对应的值构成的对组成,是另一种可变容器模型,且可存储任意类型对象。字典的每个键值用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中。

注:字典中的键是唯一的(其他类型的映射也是如此),而值不是唯一的。

字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿.即,我们把键(名字)和值(详细情况)联系在一起。注意,键必须是唯一的,字典中的键/值对是没有顺序的(字典是无序的)。如果想要一个特定的顺序,那么应该在使用前自己对它们排序。字典是dict类的实例/对象。

字典是python中唯一的内建映射类型

1.dict 函数

使用dict 函数,通过其他映射(其他字典或键-值)这样的序列对建立字典

items = [("name","zhangsan"),("age",28),("job","educator")]
D = dict(items)
print (D)
print (type(D))

2. 字典的格式化字符串

一个电话本为例子的字典代码(引用格式化字符串)

phonebook = {
"zhangsan":{
"phone":"01012345",
"addr":"tianhedong 32 hao",
},
"lisi":{
"phone":"02023456",
"addr":"huangpunan 54 hao",
},
"zhaowu":{
"phone":"03034567",
"addr":"tianhebei 17 hao",
},
"xiesen":{
"phone":"06054321",
"addr":"tianhexi 12 hao",
},
} labels ={
"phone":"phone numbers",
"addr":"address"
} name = input ("please input your name:") if "request" == "p" :key = "phone"
if "request" == "a" :key = "addr"
if name in phonebook :
print ("%s's %s is %s." %(name, labels[key], phonebook[name][key]))

字典的方法

1. clear

clear 清除字典的所有项.类似list.sort ,无返回值

D = {}
D["name"] = "xieshengsen"
D["age"] = 25 print (D) returned_value = D.clear() print (D)
print (returned_value)

2. copy

copy 返回一个具有相同键值对的新字典(浅复制)

Q = {"username":"admin","machines":["foo","bar","baz"]}
QQ = Q.copy()
print (Q)
print (QQ) QQ["username"] = "Administrator"
QQ["machines"].remove("bar") print(Q)
print(QQ)

深复制

form copy import deepcopy

import copy

d = {}
d["names"] = ["hello","world"] print (d) dd = copy.copy(d)
dc = copy.deepcopy(d)
d["names"].append("haha") print (d)
print (dd)
print(dc)

3. fromkeys

fromkeys 使用给定的键建立新的字典,每个键默认对应的值为none

print({}.fromkeys(["name","age"])) # none 作为默认值

print(dict.fromkeys(["name","age"]),"(unknown)") # 修改unknown 为默认值

4. get

get 更宽松的访问字典项的方法(一般来说,如果访问字典中不存在的项时会出错,使用get访问不会出现错误)

AA = {}
# print (AA["name"]) # 出现错误 print (AA.get("name")) # 键值不存在,输出结果None AA["name"]= "xieshengsen"
print (AA.get("name"))

5. items 和iteritems

items 方法将所有的字典项以列表方式返回,这些列表项中的每一项都是来自(键-值)。但是项在返回时并没有特殊的顺序。

II = {"title": "python web site","url":"https://www.python.org","spam":0}
print (II.items())

iteritems 会返回一个迭代器 而不是列表(python3 已经没有iteritems 这个方法)

6. keys 和iterkeys

keys 方法将字典的键以列表形式返回,而iterkeys 则返回针对键的迭代器

7. pop

pop 方法用来获取对应于给定的键的值,然后将这个键-值对从字典中移除

dd = {"hh":1,"yy":2,"vv":3,"gg":4}
print (dd.pop("hh"))
print (dd)

8. popitem

popitem 方法类似于list.pop,后者会弹出列表的最后一个元素。但,popitem弹出随机项,因为字典没有“最后元素”的概念(字典是无序的).

p = {"url":"https://www.python.org/","spam":0,"title":"python web site"}
print (p.popitem())
print (p)

9. setdefault

setdefault 类似于get方法,能够获得与给定键相关联的值,setdefault还能在字典中不含有给定键的情况下设定相应的键值

set = {}
print (set.setdefault("name","N/A"))
print (set) set["name"] = "zhangsan"
print (set.setdefault("name","N/A"))
print (set)

当键不存在时,setdefault 返回默认值并相应的更新字典,如果键存在,返回其相应值,但不改变字典。

10. update

update 方法是利用一个字典项更新另外一个字典.

up = {"color":"red","number":"1234","animal":"Bear","Fruits":"apples"}
da = {"Stationery":"book","food":"milk"}
up.update(da)
print (up)

提供的字典的项会被添加到旧字典中,相同的键会被覆盖

11. values

values 方法以列表的形式返回字典的值(itervalues 返回值的迭代器,python3 没有),与返回值的列表不同的是,返回值列表中可以包含重复的元素。

valu = {}
valu[1]=1
valu[2]=2
valu[3]=3
valu[4]=1
print (valu.values())

字典dict官方解析

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(*args, **kwargs): # real signature unknown
""" Returns a new dict with keys from iterable and values equal to value. """
pass def get(self, k, d=None): # real signature unknown; restored from __doc__
""" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
pass def items(self): # real signature unknown; restored from __doc__
""" D.items() -> a set-like object providing a view on D's items """
pass def keys(self): # real signature unknown; restored from __doc__
""" D.keys() -> a set-like object providing a view on D's keys """
pass 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__
""" 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
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then 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() -> an object providing a view on D's values """
pass def __contains__(self, *args, **kwargs): # real signature unknown
""" True if D has a key k, else False. """
pass def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
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, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" D.__sizeof__() -> size of D in memory, in bytes """
pass __hash__ = None

python--字典dict的更多相关文章

  1. python字典dict的增、删、改、查操作

    ## python字典dict的增.删.改.查操作dict = {'age': 18, 'name': 'jin', 'sex': 'male', }#增# dict['heigh'] = 185 # ...

  2. Python 字典 dict() 函数

    描述 Python 字典 dict() 函数用于创建一个新的字典,用法与 Pyhon 字典 update() 方法相似. 语法 dict() 函数函数语法: dict(key/value) 参数说明: ...

  3. 'dict_values' object does not support indexing, Python字典dict中由value查key

    Python字典dict中由value查key 众所周知,字典dict最大的好处就是查找或插入的速度极快,并且不想列表list一样,随着key的增加越来越复杂.但是dict需要占用较大的内存空间,换句 ...

  4. python 字典dict - python基础入门(15)

    前面的课程讲解了字符串str/列表list/元组tuple,还有最后一种比较重要的数据类型也需要介绍介绍,那就是python字典,俗称:dict. python中的字典可与字符串/列表/元组不同,因为 ...

  5. Python字典(dict)使用技巧

    字典dict是Python中使用频率非常高的数据结构,关于它的使用,也有许多的小技巧,掌握这些小技巧会让你高效地的使用dict,也会让你的代码更简洁. 1.默认值 假设name_for_userid存 ...

  6. python 字典 dict 该注意的一些操作

    在用python处理dict 的时候,有几个该注意的地方,这里跟大家提一下: 1)操作dict 时,尽量少产生新的列表对象.比如: 遍历dict的时候,如果用 dic = {"a" ...

  7. python 字典(dict)按键和值排序

    python 字典(dict)的特点就是无序的,按照键(key)来提取相应值(value),如果我们需要字典按值排序的话,那可以用下面的方法来进行: 1 下面的是按照value的值从大到小的顺序来排序 ...

  8. python 字典dict和列表list的读取速度问题, range合并

    python 字典和列表的读取速度问题 最近在进行基因组数据处理的时候,需要读取较大数据(2.7G)存入字典中,然后对被处理数据进行字典key值的匹配,在被处理文件中每次读取一行进行处理后查找是否在字 ...

  9. Python 字典dict 集合set

    字典dict Python内置字典,通过key-value进行存储,字典是无序的,拓展hash names = ['Michael', 'Bob', 'Tracy'] scores = [95, 75 ...

  10. 使用 json 模块,使json数据格式与Python字典dict数据格式互相转换,获取数据更加方便

    一.定义 JSON 是一种数据格式 使用 javaScript (Java 死鬼破特)对象表示法 二.特点 1.JSON 与 XML格式数据的区别 ====== 两种格式的数据,都是跨语言,跨平台 c ...

随机推荐

  1. mysql主从调优

    mysql主从同步调优 常用选项 适用于Master服务器 binlog-do-db=name 设置Master对哪些库记日志 binlog-ignore-db=name 设置Master对哪些库不记 ...

  2. LATCH_EX

    Description: This wait type occurs when a thread is waiting for access to a non-page data structure ...

  3. 解决npm ERR! Unexpected end of JSON input while parsing near的方法汇总

    参考链接:https://segmentfault.com/a/1190000015646531

  4. vux 是基于 WeUI 和Vue(2.x)开发的移动端UI组件库,主要服务于微信页面。

    https://doc.vux.li/zh-CN/ https://vux.li/

  5. Exception in thread “main” java.sql.SQLException: No suitable driver

    问题背景:通过Spark SQL的jdbc去读取Oracle数据做测试,在本地的idea中没有报任务错误.但是打包到集群的时候报: Exception in thread “main” java.sq ...

  6. jenkins 设置钉钉通知--钉钉机器人

    https://blog.csdn.net/workdsz/article/details/77531802

  7. vue--项目文件

    build config:webpack的配置文件 node_modules: 依赖的npm包 src: 项目代码 static:依赖的第三方库 ps:static中有个文件.gitkeep 因为新建 ...

  8. MongoDB--编译文件

    -j 加你的cpu核数来加速编译过程 编译出错可以自行安装所需依赖. 或者去官网直接下载编译好的二进制,直接执行. 编译好之后查看文件: mongod:mongodb的执行程序,数据库部署也用这个程序 ...

  9. ios UrlEncode与UrlDecode

    url字符串中具有特殊功能的特殊字符的字符串,或者中文字符,作为参数用GET方式传递时,需要用urlencode处理一下.当然,有时作为Post参数传递,也需要urlencode处理一下. NSStr ...

  10. lldb使用

    常用 si,ni ,ex, mem,di,reg,b,c,x 以下内容是lldb帮助文档中内容: apropos           -- List debugger commands related ...