Python起步——字典

1. 字典概念

  • 字典是一种组合的数据,没有顺序的组合数据,以键值对的形式出现。
  • 字典是序列类型,但是无序,所以没有分片和索引
  • 字典中的数据每个都是键值对(key-value)
    • key:必须可哈希,比如:int, string, float, tuple,但是list,set,dict不行
    • value: 任意值

2. 字典定义

>>> d = {}
>>> type(d)

>>> d = dict()
>>> type(d)

>>> d = {"one":1, "two":2, "three": 3}
>>> type(d)

>>> d = dict({"one":1, "two":2, "three": 3})
>>> type(d)

>>> d = dict(one=1, two=2, three = 3)
>>> d
{'two': 2, 'one': 1, 'three': 3}
>>> d = dict([("one", 1), ("two", 2), ("three", 3)])
>>> d
{'two': 2, 'one': 1, 'three': 3}

2. 字典操作

# 访问数据
>>> d = {"one":1, "two":2, "three": 3}
>>> d
{'two': 2, 'one': 1, 'three': 3}
>>> d["one"]
1
>>> d.get("one")
1
>>> d["one"]
1
>>> d.get("sag")
>>> d.get("sag", 100)
100
>>> d["sag"]
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 'sag'
# 删除数据
>>> d = {"one":1, "two":2, "three": 3}
>>> d
{'two': 2, 'one': 1, 'three': 3}
>>> d["one"]
1
>>> del d["three"]
>>> d
{'two': 2, 'one': 1}
# 成员检测(检测的是键key内容)
>>> 2 in d
False
>>> 'two' in d
True
>>> ("two", 2) in d
False

3. 字典遍历

python2 和python3区别较大。

# code
d = {"one":1, "two":2, "three":3}
for k in d:
    print(k, d[k])

for k in d.keys():
    print(k, d[k])

for k,v in d.items():
    print(k, "---", v)
# python3 输出
three 3
one 1
two 2
three 3
one 1
two 2
three --- 3
one --- 1
two --- 2
# python2 输出
('three', 3)
('two', 2)
('one', 1)
('three', 3)
('two', 2)
('one', 1)
('three', '---', 3)
('two', '---', 2)
('one', '---', 1)

4. 字典生成式

>>> d = {"one":1, "two":2, "three": 3}
>>> dd = {k:v for k, v in d.items()}
>>> dd
{'two': 2, 'one': 1, 'three': 3}
>>> dd = {k:v for k,v in d.items() if v % 2 == 0}
>>> dd
{'two': 2}
# fromkeys()
>>> l = ['one', 'two', 'three']
>>> d = dict.fromkeys(l, "num")
>>> d
{'two': 'num', 'one': 'num', 'three': 'num'}

5. 字典相关函数

  • 通用函数:len,max,min, dict
# str(): 返回字典的字符串格式
>>> d = {"one":1, "two":2, "three": 3}
>>> str(d)
"{'two': 2, 'one': 1, 'three': 3}"
# clear(): 清除字典
# items(): 返回字典键值对的元组格式
----
# python 3:输出
>>> i = d.items()
>>> type(i)

>>> i
dict_items([('two', 2), ('one', 1), ('three', 3)])
>>> k = d.keys()
>>> k
dict_keys(['two', 'one', 'three'])
>>> v = d.values()
>>> v
dict_values([2, 1, 3])
----
# python 2:输出
>>> d = {"one":1, "two":2, "three": 3}
>>> i = d.items()
>>> type(i)

>>> i
[('three', 3), ('two', 2), ('one', 1)]
>>> k = d.keys()
>>> k
['three', 'two', 'one']
>>> v = d.values()
>>> v
[3, 2, 1]
---

你可能感兴趣的:(Python起步——字典)