栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python学习——字典

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python学习——字典

字典

字典:是一系列键值对

键值对:指两个相关联的值,包括键和值,每个键都与一个值(数、字符串、列表或字典均可)相关联,指定键时,python将返回与之相关联的值

键与值之间用冒号分隔,而键值对之间用逗号分隔

使用字典 创建字典

使用一对花括号{}定义一个字典,再分行添加各个键值对

alien_0={}
alien_0['color']='green'
alien_0['point']=5
print(alien_0)
访问字典中的值

获取与键相关联的值,可依次指定字典名和放在方括号里的键

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

为避免指定的键不存在的问题,可使用**get()**访问值

方法get()的第一个参数用于指定键,是必不可少的;第二个参数为指定的键不存在时要返回的值,时可选的,若第二个参数没有指定,python将返回值none

alien_0={'color':'green'}
point_value=alien_0.get('points','No point value assigned.')
print(point_value)
添加键值对

需指定字典名、用方括号括起的键和相关联的值*

字典中元素的排列顺序与定义时(添加顺序)相同

alien_0={'color':'green','points':5}
alien_0['x_position']=0
alien_0['y_position']=25
print(alien_0)
修改字典中的值

需依次指定字典名、用方括号括起的键,与该键相关联的新值

alien_0={'color':'green','points':5}
alien_0['color']='yellow'

若与if语句结合:

alien_0={'x_position':0,'y_position':25,'speen':'medium'}
#依据当前速度确定将外星人向右移动多远
if alien_0['speed']=='slow':
   x_increment=1
elif alien_0['speed']=='medium':
   x_increment=2
else:
   x_increment=4
#新位置为旧位置加上移动位置
alien_0['x_position']=alien_0['x_position']+x_increment
print(f"New position:{alien_0['x_position']}")
删除键值对

使用del语句将相应的键值对永久彻底删除

alien_0={'color':'green','points':5}
del alien_0['points']
较长的字典格式设置方式

可将较大的字典放在多行中,在输入左花括号后按回车键,在下一行缩进四个空格,指定第一个键值对,并在它后面加逗号,再按回车键,在最后一个键值对后面加上逗号,在最后一个键值对的下一行添加一个右花括号,并缩进四个空格,使其与字典中的键对齐

favorite_languages={
    'fen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
遍历字典 遍历所有键值对

使用for循环遍历字典,需声明两个变量(用于存储键值对中的键和值,可以使用任意名称)

user_0={
    'username':'efermi',
    'first':'enrico',
    'last':'fermi',
    }
for key, value in user_0.items():
    print(f'nKey: {key}')
    print(f'Value': {value})
遍历所有键

使用keys()

favorite_languages={
    'fen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
for name in favorite_languages.keys():
    print(name.title())

还可与if语句结合,使用当前键来访问与之相关联的值

favorite_languages={
    'fen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
friends=['phil','sarah']
for name in favorite_languages.keys():
    print(f'Hi {name.title()}.')
    if name in friends:
    #获得相应的语言,使用字典名,将变量name的当前值作为键
       language=favorite_language[name].title()
       print(f't{name.title()},I see you love {language}!')

确定某个键是否在字典中

favorite_languages={
    'fen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
if 'erin' not in favorite_languages.keys():
    print('Erin, please take your poll!')
按特定顺序遍历字典中所有键
favorite_languages={
    'fen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
for name in sorted(favorite_languages.keys()):
    print(name.title())
遍历字典中所有值

使用values()

favorite_languages={
    'fen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
print('The follwing languages have been mentioned:')
for name in favorite_languages.values():
    print(name.title())

set()集合:剔除重复项,集合中的每个元素都时独一无二的,用{}表示,不会以特定的顺序存储元素

集合与字典区别:花括号内没有键值对时,定义的很可能时集合

favorite_languages={
    'fen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
for name in set(favorite_languages.values()):
    print(name.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)

使用range()代码自动生成的情况:

#创建一个空列表
aliens=[]
#创建30个绿色外星人
for alien_number in range(30):
    new_alien={'color':'green','points':5,'speed':'slow'}
    aliens.append(new_alien)
#对前3个进行修改
for alien in aliens[:3]:
    if alien['color']=='green':
       alien['color']='yellow'
       alien['speed']='medium'
       alien['points']=10
    #再修改为红色
    elif alien['color']=='yellow':
       alien['color']='red'
       alien['speed']='fast'
       alien['points']=15
#显示前5个
for alien in aliens[:5]:
    print(alien)
列表嵌套在字典中
favorite_languages={
    'fen':['python','ruby'],
    'sarah':['c'],
    'edward':['ruby','go'],
    'phil':['python','haskell'],
    }
for name, languages in favorite_languages.items():
    print(f"n{name.title()}'s favorite languages are:")
    for language in languages:
        print(f't{language.title()}')
字典嵌套在字典中
users={
    'aeinstein':{
        'first':'albert',
        'last':'einstein',
        'location':'princeton',
        },
    'mvurie':{
        'first':'marie',
        'last':'curie',
        'location':'patis',
        }
    }
for username,user_info in users.items():
    print(f'nUsername:{username}')
    full_name=f"{user_info['first']} {user_info['last']}"
    location=user_info['location']
    print(f'tFull name:{ full_name.title()}')
    print(f'tLocation:{ location.title()}')
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/968395.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号