字典的创建
字典是序列类型,但是无序,不可索引和切片每个数据都由键值对组成,即kv对
key:可哈希的值,比如str、int、float,但list、tuple、dict不行value:任何值
k
= {}
print(k
)
d
= dict()
print(d
)
d
= {"one":555, "two":666, "three":777}
print(d
)
d
= dict({"one":555, "two":666, "three":777})
d
= dict(one
=555, two
=666, three
=777)
print(d
)
d
= dict([("one",555),("two",666),("three",777)])
print(d
)
'''
{}
{}
{'one': 555, 'two': 666, 'three': 777}
{'one': 555, 'two': 666, 'three': 777}
{'one': 555, 'two': 666, 'three': 777}
'''
字典的常见操作
d
= {"one":555, "two":666, "three":777}
print(d
["one"])
d
["one"] = 111
print(d
)
del d
["one"]
print(d
)
'''
555
{'one': 111, 'two': 666, 'three': 777}
{'two': 666, 'three': 777}
'''
d
= {"one":555, "two":666, "three":777}
if "one" in d
:
print("key")
if 555 in d
:
print("value")
if ("one",555) in d
:
print("k,v")
字典的遍历
d
= {"one":555, "two":666, "three":777}
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
)
print("*" * 50)
for k
in d
:
print(k
)
'''
one 555
two 666
three 777
one 555
two 666
three 777
555
666
777
one --- 555
two --- 666
three --- 777
**************************************************
one
two
three
'''
字典的生成
d
= {"one":555, "two":666, "three":777}
dd
= {k
:v
for k
,v
in d
.items
()}
print(dd
)
ddd
= {k
:v
for k
,v
in d
.items
() if v
% 2 == 0}
print(ddd
)
'''
{'one': 555, 'two': 666, 'three': 777}
{'two': 666}
'''
字典的相关函数
d
= {"one":555, "two":666, "three":777}
d1
= str(d
)
print(d1
)
print(type(d1
))
d2
= d
.items
()
print(d2
)
print(type(d2
))
d3
= d
.keys
()
print(d3
)
print(type(d3
))
d4
= d
.values
()
print(d4
)
print(type(d4
))
'''
{'one': 555, 'two': 666, 'three': 777}
<class 'str'>
dict_items([('one', 555), ('two', 666), ('three', 777)])
<class 'dict_items'>
dict_keys(['one', 'two', 'three'])
<class 'dict_keys'>
dict_values([555, 666, 777])
<class 'dict_values'>
'''
d
= {"one":555, "two":666, "three":777}
print(d
.get
("one33"))
print(d
.get
("one33",100))
print(d
["one33"])
'''
None
100
KeyError
'''
l
= ["one", "two", "three"]
d
= dict.fromkeys
(l
, "这就是一个值")
print(d
)
转载请注明原文地址: https://yun.8miu.com/read-110695.html