简介
字典是一种可变容器模型,且可存储任意类型对象,字典的每个键值 key=>value
对用冒号:
分割,每个键值对之间用逗号 ,
分割,整个字典包括在花括号{}
中 ,如:
object = {
'color': 'yellow',
'size': 'big'
}
print(object['color'])
print(object['size'])
添加键值对
object['age'] = 18
object['sex'] = 'man'
print(object)
创建一个空字典
object = {}
object['color'] = 'yellow'
object['size'] = 'big'
print(object)
修改字典中的值
object['color'] = 'black'
print(object)
删除键值对
object = {'color': 'black', 'age': 18}
del object['color']
print(object)
遍历键值对
user = {
'username': 'coisini',
'age': '18',
'sex': 'man'
}
for key,value in user.items():
print('key:' + key)
print('value:' + value)
遍历所有键值
use_languages = {
'one_user': 'python',
'two_user': 'c',
'three_user': 'ruby',
'four_user': 'python'
}
for key in use_languages.keys():
print('key:' + key)
print('value:' + use_languages[key])
if key == 'one_user':
print('one_user is in use_languages')
use_languages.key() 简写为use_languages
if 'four_user' in use_languages:
print('four_user is in use_languages')
顺序遍历所有键值
for name in sorted(use_languages.keys()):
print(name.title())
遍历字典中的所有值
for language in use_languages.values():
print(language.title())
使用集合(set)剔除重复项
for language in set(use_languages.values()):
print(language.title())
列表字典嵌套
one_user = {'color': 'black', 'age': 5}
two_user = {'color': 'white', 'age': 10}
three_user = {'color': 'yellow', 'age': 15}
users = [one_user, two_user, three_user]
for user in users:
print(user)
字典列表嵌套
user = {
'username': 'coisini',
'languages': ['Java', 'Python']
}
for language in user['languages']:
print(' ' + language)
字典字典嵌套
users = {
'coisini': {
'name': 'coisini',
'age': 18,
'location': 'China'
},
'maggieq': {
'name': 'maggieq',
'age': '22',
'location': 'Canada'
}
}
for username, userinfo in users.items():
print('
username:' + username)
for key, val in users[username].items():
print(' key:' + str(key))
print(' val:' + str(val))