字典 是一系列键值对,如:
>>> person = {'name' : 'jack', 'age' : 18}
>>> person['age']
18
值可以是数字、字符串、列表、字典以及任何python类型的数据
添加键值
>>> person['height'] = 175
>>> print(person)
{'name': 'jack', 'age': 18, 'height': 175}
空字典
>>> person = {}
>>> person['name'] = 'Tom'
>>> print(person)
{'name': 'Tom'}
修改值
>>> person['name'] = 'Tommy'
>>> print(person)
{'name': 'Tommy'}
删除键值对
>>> del person['name']
>>> print(person)
{}
遍历字典
利用字典的items(), keys(), values() 方法进行遍历
>>> person = {'name' : 'Tom', 'age' : 18, 'height' : 175}
>>> for item in person.items():
... print(item)
...
('name', 'Tom')
('age', 18)
('height', 175)
可以发现每一个item是一个元组,可以用print(type(item))进行验证
>>>
>>> for key, value in person.items():
... print(key + ':' + str(value))
...
name:Tom
age:18
height:175
>>> for key in person.keys():
... print(key)
...
name
age
height
>>> for value in person.values():
... print(value)
...
Tom
18
175
嵌套
>>> person1 = {'name' : 'Tom', 'age' : 18, 'height' : 170}
>>> person2 = {'name' : 'Jack', 'age' : 20, 'height' : 178}
>>> person3 = {'name' : 'Rose', 'age' : 18, 'height' : 166}
>>> persons = [person1, person2, person3]
>>> print(persons)
[{'name': 'Tom', 'age': 18, 'height': 170}, {'name': 'Jack', 'age': 20, 'height' : 178}, {'name': 'Rose', 'age': 18, 'height': 166}]
>>> cities1 = ['beijing', 'shanghai']
>>> cities2 = ['shanghai', 'hangzhou', 'nanjing']
>>> favorite_cities = {'xiaoming' : cities1, 'xiaowang' : cities2}
>>> print(favorite_cities)
{'xiaoming': ['beijing', 'shanghai'], 'xiaowang': ['shanghai', 'hangzhou', 'nanjing']}
本文内容到此结束,更多内容可关注公众号和个人微信号: