1 创建字典
person = {'name':'fmxd', 'age':1, 'sex':'boy'}
2 操作字典
2.1 获取其中的数据
age = person['age']
2.2 添加属性
person[food] = 'milk'
2.3 修改属性值
father = {}
father['name'] = 'fxd'
father['age'] = 25
father['sex'] = 'male'
2.4 删除属性值
del person['age']
3 遍历字典
3.1 遍历键值对
for key, value in person.items():
#doSomeThing with key or value
3.2 遍历键
for key in person.keys():
#doSomeThing with key
注:获取的时候不一定是排序的,需要排序可以使用如下代码
for key in sorted(person.keys()):
3.3.遍历值
for value in person.values():
#doSomeThing with value
4 嵌套
4.1 字典嵌套列表
格式如下
map = {'key1':[list1], 'key2':'value2', ...}
4.2 列表嵌套字典
格式如下
list = [map1, map2, map3 ...]
4.3 字典嵌套字典
格式如下
map = {'key1':map1, 'key2':map2 ...}
5 练习
代码
#import this
#创建一个字典
person = {'name':'fmxd', 'age':3, 'sex':'boy'}
print('The child is a '+ person['sex'] + ',he is '+ str(person['age']) + ' years old ,and his name is '+ person['name'] + '.')
#添加属性
person['food'] = 'milk'
print('His favorite food is ' + person['food'] + '.')
#修改属性值
father = {}
father['name'] = 'fxd'
father['age'] = 25
father['sex'] = 'male'
person['father'] = father['name']
print('His father is '+ father['name'] + ',he is '+ str(father['age']) + ' years old last year.')
father['age'] = 26
print('And this year Mr.fxd is '+ str(father['age']) + ' years old.')
#删除属性值
del person['age']
print('Let us make the boy' + '\'' + 's age is a ecret:')
print(str(person) + '.')
#遍历字典
#遍历键值对
mother = {}
mother['name'] = 'hfx'
mother['age'] = 25
mother['sex'] = 'female'
person['mother'] = mother['name']
for key, value in mother.items():
print('His mother' + '\'' + key + ' is ' + str(value))
#遍历键
for key in father.keys():
print('His father' + '\'' + key + ' is ' + str(father[key]))
#嵌套
family = [person, father, mother]
print('The happy family is')
print(family)
输出
The child is a boy,he is 3 years old ,and his name is fmxd.
His favorite food is milk.
His father is fxd,he is 25 years old last year.
And this year Mr.fxd is 26 years old.
Let us make the boy's age is a ecret:
{'name': 'fmxd', 'sex': 'boy', 'food': 'milk', 'father': 'fxd'}.
His mother'name is hfx
His mother'age is 25
His mother'sex is female
His father'name is fxd
His father'age is 26
His father'sex is male
The happy family is
[{'name': 'fmxd', 'sex': 'boy', 'food': 'milk', 'father': 'fxd', 'mother': 'hfx'}, {'name': 'fxd', 'age': 26, 'sex': 'male'}, {'name': 'hfx', 'age': 25, 'sex': 'female'}]