Python - 字典(dict) 详解 及 代码

时间:2022-11-30 06:07:54

字典(dict) 详解 及 代码

本文地址: http://blog.csdn.net/caroline_wendy/article/details/17291329

字典(dict)是表示映射的数据结构,key-value形式, key必须是唯一的;

items()方法, 返回字典的所有项;

可以通过for循环去遍历字典的键(key)和值(value), 也可以使用if判断元素是否存在;

可以通过len()求字典的长度;下标操作符("[]")增加和删除元素;

代码:

# -*- coding: utf-8 -*-

#====================
#File: abop.py
#Author: Wendy
#Date: 2013-12-03
#==================== #eclipse pydev, python3.3 #字典, 即map, dict an = { 'Caroline' : 'A beautiful girl.',
'Wendy' : 'A talent girl.',
'Spike' : 'A good boy'
} print (an)
print ("Who is Caroline?", an['Caroline'])
del an['Spike']
print('There are {0} girls.'.format(len(an))) for name, property in an.items() : #遍历字典的项
print('{0} is that {1}'.format(name, property)) an['Ruby'] = 'A pretty girl' if 'Ruby' in an : #判断元素是否存在
print("The new one Ruby is that", an['Ruby'])

输出:

{'Caroline': 'A beautiful girl.', 'Wendy': 'A talent girl.', 'Spike': 'A good boy'}
Who is Caroline? A beautiful girl.
There are 2 girls.
Caroline is that A beautiful girl.
Wendy is that A talent girl.
The new one Ruby is that A pretty girl

Python - 字典(dict) 详解 及 代码