字典类型
字典类型以键值对的形式存储多个值
fruits = {'apple': '苹果', 'banana': '香蕉', 'carrot': '萝卜'}
print(fruits)
print(type(fruits))
print(len(fruits))
print(fruits['apple'])
print(fruits['banana'])
print(fruits['carrot'])
{'apple': '苹果', 'banana': '香蕉', 'carrot': '萝卜'}
<class 'dict'>
3
苹果
香蕉
萝卜
如类型名所示,使用方法类似于字典,输入键查询值
操作
键值对的追加
fruits = {'apple': '苹果', 'banana': '香蕉', 'carrot': '萝卜'}
print(fruits)
fruits['durian'] = '榴莲'
print(fruits)
{'apple': '苹果', 'banana': '香蕉', 'carrot': '萝卜'}
{'apple': '苹果', 'banana': '香蕉', 'carrot': '萝卜', 'durian': '榴莲'}
值的变更
fruits = {'apple': '苹果', 'banana': '香蕉', 'carrot': '萝卜'}
print(fruits)
fruits['carrot'] = '人参'
print(fruits)
{'apple': '苹果', 'banana': '香蕉', 'carrot': '萝卜'}
{'apple': '苹果', 'banana': '香蕉', 'carrot': '人参'}
键值对的削除
fruits = {'apple': '苹果', 'banana': '香蕉', 'carrot': '萝卜', 'durian': '榴莲'}
print(fruits)
del fruits['durian']
print(fruits)
{'apple': '苹果', 'banana': '香蕉', 'carrot': '萝卜', 'durian': '榴莲'}
{'apple': '苹果', 'banana': '香蕉', 'carrot': '萝卜'}
键查找
fruits = {'apple': '苹果', 'banana': '香蕉', 'carrot': '萝卜', 'durian': '榴莲'}
target = 'egg'
if target in fruits:
print('字典含键%s' % target)
else:
print('字典不含键%s' % target)
字典不含键egg
取键值对
基本形式
for 键参数, 值参数 in 字典名.items():
处理语句
如
n = {'apple': '苹果',
'banana': '香蕉',
'carrot': '萝卜',
'durian': '榴莲'}
i = 1
for a, b in n.items():
print(a, b, '%d个' %i)
i += 1
apple 苹果 1个
banana 香蕉 2个
carrot 萝卜 3个
durian 榴莲 4个
取键
基本形式
for 键参数 in 字典名.keys():
处理语句
如
n = {'apple': '苹果',
'banana': '香蕉',
'carrot': '萝卜',
'durian': '榴莲'}
i = 1
for a in n.keys():
print(a, '%d个' %i)
i += 1
apple 1个
banana 2个
carrot 3个
durian 4个
取值
n = {'apple': '苹果',
'banana': '香蕉',
'carrot': '萝卜',
'durian': '榴莲'}
i = 1
for a in n.values():
print(a, '%d个' %i)
i += 1
苹果 1个
香蕉 2个
萝卜 3个
榴莲 4个