Python 字典

字典的特性:

▷ key - value 结构
▷ key 必须可 hash, 且必须为不可变数据类型, 必须唯一
▷ 可存放任意多个值, 可修改, 可以不唯一
▷ 无序, 所以字典无索引
▷ 查找快速

dic = {'susan':['女',28,'IT','alibaba']}
dic['susan']
>>> ['女', 28, 'IT', 'alibaba']
dic['susan'][0]
>>> '女'

字典的遍历:

dic2 = {'susan':'IT','ada':'singer','ak47':'gun'}

1. 遍历 key 值:

    for k in dic2:
        print(k,dic2[k])
>>> susan IT
    ada singer
    ak47 gun

    for k in dic2.keys():
        print(k,dic2[k])
>>> susan IT
    ada singer
    ak47 gun

在使用上, for k in dic2 与 for k in dic2.keys() 完全等价.

2. 遍历 value 值:

    for v in dic2.values():
        print(v)
>>> IT
    singer
    gun

3. 遍历字典项:

    for k in dic2.items():
        print(k)
>>> ('susan', 'IT')
    ('ada', 'singer')
    ('ak47', 'gun')

4. 遍历字典键值:

    for k,v in dic2.items():
        print(k,v)
>>> susan IT
    ada singer
    ak47 gun

修改字典:

1. 增加新的键值对:

    dic3 = {}
    dic3['name']='ada'
    dic3
>>> {'name': 'ada'}

2. 修改键值对:

    dic3['name']='xiaojiba'
    dic3
>>> {'name': 'xiaojiba'}

删除字典:

    dic4 = {'name':'xiaojiba','home':'beijing','job':'gamer'}
    dic4
>>> {'name': 'xiaojiba', 'home': 'beijing', 'job': 'gamer'}

1. del 删除键值对

    del dic4['home']
    dic4
>>> {'name': 'xiaojiba', 'job': 'gamer'}

2. clear 清空字典

    dic4.clear()
    dic4
>>> {}

3. del 字典 ------> 字典被删除, dic4 然后会报错, 字典 not defined

    del dic4
    dic4
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'dic4' is not defined

字典 get 方法:

    dic4 = {'name':'xiaojiba','home':'beijing','job':'gamer'}
    dic4
>>> {'name': 'xiaojiba', 'home': 'beijing', 'job': 'gamer'}
    dic4.get('name')
>>> 'xiaojiba'

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