码迷,mamicode.com
首页 > 编程语言 > 详细

Python基础之dictionary

时间:2021-01-12 10:47:29      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:添加   图片   集合   value   对象   man   pytho   users   values   

简介

字典是一种可变容器模型,且可存储任意类型对象,字典的每个键值 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(‘\t‘ + language)
字典字典嵌套
users = {
	‘coisini‘: {
		‘name‘: ‘coisini‘,
		‘age‘: 18,
		‘location‘: ‘China‘
	},
	‘maggieq‘: {
		‘name‘: ‘maggieq‘,
		‘age‘: ‘22‘,
		‘location‘: ‘Canada‘
	}
}

for username, userinfo in users.items():
	print(‘\nusername:‘ + username)
	
	for key, val in users[username].items():
		print(‘\tkey:‘ + str(key))
		print(‘\tval:‘ + str(val))
- End -
一个努力中的公众号
关注一下吧
技术图片

Python基础之dictionary

标签:添加   图片   集合   value   对象   man   pytho   users   values   

原文地址:https://www.cnblogs.com/maggieq8324/p/14255578.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!