字典

coding=gbk

一个简单的字典

alien_0={'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])

字典是一系列键-值对,与键相关联的值可以是数字字符串列表乃至字典

添加键-值对

alien_0={'color‘:'green’,'points':5}
print(alien_0)
    
alien_0['x_positon']=0
alien_0['y_positon']=25
print(alien_0)
{'color‘:'green’,'points':5}
{'color‘:'green’,'points':5,'x_positon',0,'y_positon',25}

修改字典中的值

alien_0['color']=yellow

删除键-值对

del alien_0['points']

遍历所有的键-值对

for key,value in alien_0.items():
    print("\nKey:"+key)
    print("Value:"+value)

key,value可以更换为其他变量来让人更容易理解

遍历字典中所有的键

用keys()方法,也可以省略keys()

for color in alien_0.keys()
    print(color.title())

按顺序遍历字典中的所有键

favorite_language={
    'jen':'python',
    'sarah':'c',
    'edward':,'ruby',
    'phil':'python',
    }
for name in sorted(favorite_language.keys()):
    print(name.title() + ",thank you for taking the poll.")
方法sorted()对字典中的键进行升序排列

遍历字典中的所有键

可使用方法values()
为剔除重复项,可使用集合(set)
favorite_languages={
    'jen':'python',
    'sarah':'c',
    'edward':,'ruby',
    'phil':'python',
    }
print('the following language have been mentioned:')
for language in set(favorite_languages.values()):
    print(language.title())

嵌套

字典列表

#创建三个字典,每个字典代表一个外星人,
#再将这些字典放到一个列表中。
alien_0={'color':'green','points':5}
alien_1={'color':'yellow','points':10}
alien_2={'color':'red','points':15}

aliens=[alien_0,alien_1,alien_2]

for alien in aliens:
    print(alien)
#创建30个绿色外星人
aliens=[]
for alien_number in range(30):
    new_alien={'color':'green','points':5,'speed':'slow',}
    aliens.append(new_alien)
#显示前5个外星人
for alien in aliens[:5]:
    print(alien)
print("...")
#显示创建了多少个外星人
print('Totle number of aliens: ' + str(len(aliens)))

字典中存储列表

#存储所点披萨信息
pizza={
	'crust':'thick',
	'toppings':['mushrooms','extra cheese'],
	}
#概述所点的披萨
print('You ordered a ' + pizza['crust'] + '-crust pizza ' +
	'with the following  toppings:')
for topping in pizza['toppings']:
	print('\t' + topping)

在字典中存储字典

users={
	'aeinstein':{
		'first':'albert',
		'last':'einstein',
		'location':'princeton',
		},
	'mcurie':{
		'first':'marie',
		'last':'curie',
		'location':'paris',
		},
	}
for username,user_info in users.items():
	print('\nusername: ' + username)
	full_name=user_info['first'] + ' ' + user_info['last']
	location=user_info['location']
	print('\tFull name: ' + full_name.title() )
	print('\tLocation: ' + location.title())
posted @ 2018-12-06 23:12  Rener  阅读(107)  评论(0编辑  收藏  举报