Python中字典dict

dict字典

  • 字典是一种组合数据,没有顺序的组合数据,数据以键值对形式出现
# 字典的创建
# 创建空字典1
d = {}
print(d)

# 创建空字典2
d = dict()
print(d)

# 创建有值的字典, 每一组数据用冒号隔开, 每一对键值对用逗号隔开
d = {"one":1, "two":2, "three":3}
print(d)

# 用dict创建有内容字典1
d = dict({"one":1, "two":2, "three":3})
print(d)

# 用dict创建有内容字典2
# 利用关键字参数
d = dict(one=1, two=2, three=3)
print(d)

#
d = dict( [("one",1), ("two",2), ("three",3)])
print(d)
{}
{}
{‘one‘: 1, ‘two‘: 2, ‘three‘: 3}
{‘one‘: 1, ‘two‘: 2, ‘three‘: 3}
{‘one‘: 1, ‘two‘: 2, ‘three‘: 3}
{‘one‘: 1, ‘two‘: 2, ‘three‘: 3}

字典的特征?

  • 字典是序列类型,但是是无序序列,所以没有分片和索引
  • 字典中的数据每个都有键值对组成,即kv对
    • key: 必须是可哈希的值,比如int,string,float,tuple, 但是,list,set,dict 不行
    • value: 任何值

字典常见操作

# 访问数据
d = {"one":1, "two":2, "three":3}
# 注意访问格式
# 中括号内是键值
print(d["one"])

d["one"] = "eins"
print(d)

# 删除某个操作
# 使用del操作
del d["one"]
print(d)
1
{‘one‘: ‘eins‘, ‘two‘: 2, ‘three‘: 3}
{‘two‘: 2, ‘three‘: 3}
# 成员检测, in, not in
# 成员检测检测的是key内容,键
d = {"one":1, "two":2, "three":3}

if 2 in d:
    print("value")

if "two" in d:
    print("key")

if ("two",2) in d:
    print("kv")
key可以看出,字典dict中的成员检测为键,因为它具有唯一性
# 便利在python2 和 3 中区别比较大,代码不通用
# 按key来使用for循环
d = {"one":1, "two":2, "three":3}
# 使用for循环,直接按key值访问
for k in d:
    print(k,  d[k])

# 上述代码可以改写成如下  提倡这么写
for k in d.keys():
    print(k,  d[k])

# 只访问字典的值
for v in d.values():
    print(v)

# 注意以下特殊用法
for k,v in d.items():
    print(k,‘--‘,v)
one 1
two 2
three 3
one 1
two 2
three 3
1
2
3
one -- 1
two -- 2
three -- 3
# 常规字典生成式
dd = {k:v for k,v in d.items()}
print(dd)

# 加限制条件的字典生成式 过滤文件
dd = {k:v for k,v in d.items() if v % 2 == 0}
print(dd)
{‘one‘: 1, ‘two‘: 2, ‘three‘: 3}
{‘two‘: 2}

字典相关函数

# 通用函数: len, max, min, dict
# str(字典): 返回字典的字符串格式
d = {"one":1, "two":2, "three":3}
print(d)
{‘one‘: 1, ‘two‘: 2, ‘three‘: 3}
# clear: 清空字典
# items: 返回字典的键值对组成的元组格式

d = {"one":1, "two":2, "three":3}
i = d.items()
print(type(i))
print(i)
<class ‘dict_items‘>
dict_items([(‘one‘, 1), (‘two‘, 2), (‘three‘, 3)])
# keys:返回字典的键组成的一个结构
k = d.keys()
print(type(k))
print(k)
<class ‘dict_keys‘>
dict_keys([‘one‘, ‘two‘, ‘three‘])
# values: 同理,一个可迭代的结构
v = d.values()
print(type(v))
print(v)
<class ‘dict_values‘>
dict_values([1, 2, 3])
# get: 根据制定键返回相应的值, 好处是,可以设置默认值

d = {"one":1, "two":2, "three":3}
print(d.get("on333"))

# get默认值是None,可以设置
print(d.get("one", 100))
print(d.get("one333", 100))

#体会以下代码跟上面代码的区别
print(d[‘on333‘])
None
1
100
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-74-7a2a24f5a7b6> in <module>()
      9
     10 #体会以下代码跟上面代码的区别
---> 11 print(d[‘on333‘])

KeyError: ‘on333‘
# fromkeys: 使用指定的序列作为键,使用一个值作为字典的所有的键的值
l = ["eins", "zwei", "drei"]
# 注意fromkeys两个参数的类型
# 注意fromkeys的调用主体
d = dict.fromkeys(l, "hahahahahah")
print(d)
{‘eins‘: ‘hahahahahah‘, ‘zwei‘: ‘hahahahahah‘, ‘drei‘: ‘hahahahahah‘}

原文地址:https://www.cnblogs.com/cswzp/p/10000353.html

时间: 2024-08-30 06:05:08

Python中字典dict的相关文章

python中字典dict的操作

字典可存储任意类型的对象,由键和值(key - value)组成.字典也叫关联数组或哈希表. dict = {'A' : 001 , 'B' : '002' , 'C' : [1 , 2 , 3] } dict['A'] = 007 # 修改字典元素 dict['D'] = (5 , 6 , 7) # 增加字典元素 del dict['A'] # 删除字典元素 del dict # 删除字典 dict.clear() # 清除字典所有元素 len(dict) # 字典元素个数 str(dict)

《python源码剖析》笔记 python中的Dict对象

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie 1.PyDictObject对象 -->  C++ STL中的map是基于RB-tree的,搜索时间复杂度是O(logN) PyDictObject采用了hash表,时间复杂度是O(1) typedef struct{ Py_ssize_t me_hash; //me_key的hash值,避免每次查询都要重新计算一遍hash值 PyObject *me_key; PyObject *me_

《python源代码剖析》笔记 python中的Dict对象

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie 1.PyDictObject对象 -->  C++ STL中的map是基于RB-tree的,搜索时间复杂度是O(logN) PyDictObject採用了hash表,时间复杂度是O(1) typedef struct{ Py_ssize_t me_hash; //me_key的hash值,避免每次查询都要又一次计算一遍hash值 PyObject *me_key; PyObject *me

python 中字典、数组

a = {"k1":"v1","A":1,"a":2,5:"i5"} a["A"] ="直接修改" a["aa"]="没有的键是新建" del a["a"] #删除一个元素 d.clear() #清空一个字典 1.字典是键值对,没有顺序, 2.键大小写敏感 3.键值可以是混合类型的 b = ["a&

Python中字典get方法的使用

Python中字典get方法的使用 说起来,这个功能是否需要学习还真是有待于讨论.其实,知道了字典这种数据结构以后,通过最基本的Python功能也能够实现一个类似的功能.不过,既然内置了这个功能那么我们就没有必要重复造车轮. 在字典内置的方法中,想说的方法为get.这个方法是通过键来获取相应的值,但是如果相应的键不存在则返回None.其实,None只是一个默认的返回值但是并不是一个不能修改的返回值.其实,如果查询失败,我们可以指定一个返回值. 上面提到的所有功能汇总在一个示范代码,具体如下: #

python中字典的使用

python中的字典的特性: 在字典中的元素是散列存放的,没有顺序, 在进行增删改查的时候使用字典中需要的关键字(key)即可. 一: 创建字典 1)直接定义一个: dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'} 注: 字典中可包含列表:dict={'yangrong':['23','IT'],"xiaohei":['22','dota']} 字典中可包含字典:dict={'yangrong':{"age&q

Python中字典和集合

映射类型: 表示一个任意对象的集合,且可以通过另一个几乎是任意键值的集合进行索引 与序列不同,映射是无序的,通过键进行索引 任何不可变对象都可用作字典的键,如字符串.数字.元组等 包含可变对象的列表.字典和元组不能用作键 引用不存在的键会引发KeyError异常 1)字典 dict { } 空字典 { key1:value1,key2:value2,... } 字典在其它编程语言中又称作关联数组或散列表: 通过键实现元素存取:无序集合:可变类型容器,长度可变,异构,嵌套 支持的操作: len(D

Python中的dict

# dict # Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度. d = {'Michael': 95, 'Bob': 75, 'Tracy': 85} print('dict get Michael:', d['Michael']) # add a element d['Adam'] = 67 print('dict d', d) # change a element d['Adam

python中字典,元组,集合

python中的字典,元组,集合 -dict -tuple -set dict 字典增删改查 字典创建 my_dict = {'a':1,'b':2} my_dict {'a': 1, 'b': 2} de8ug = {'name':'de8ug', 'city':'beijing', 'code':'python'} #个人信息 de8ug['name'] 'de8ug' de8ug['city'] 'beijing' de8ug.get('name') #尝试去获取name的值 'de8ug