《python编程:从入门到实践》极简笔记:字典

一个简单的字典

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

使用字典

字典是一系列键-值对。每个键都与一个值相关联。与键相关联的值可以是任何对象,数字、字符串、列表乃至字典。

添加键-值对

要添加键-值对,可依次指定字典名、用方括号括起来的键和相关联的值

alien={'color':'green','points':5}
print(alien)
alien['x_position']=0
alien['y_position']=25
print(alien)
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

键-值对的排列顺序与添加顺序不同

先创建一个空字典

先创建一个空字典,再添加键-值对

alien={}
alien['color']='green'
alien['points']=5
print(alien)

{'color': 'green', 'points': 5}

修改字典中的值

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

删除键-值对

可用del语句删除。使用del时,必须指定字典名和要删除的键

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

由类似对象组成的字典

调查不同的人喜欢的编程语言

lang={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
print("sarah's favorite language is "+lang['sarah'].title()+'.')
sarah's favorite language is C.

注意格式,很有用。

遍历字典

遍历所有的键-值对

用方法items()返回一个键-值对列表,再用for循环

lang={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
for name,language in lang.items():
    print("\nname: "+name)
    print("language: "+language)
name: jen
language: python

name: sarah
language: c

name: edward
language: ruby

name: phil
language: python

返回顺序可能与存储顺序不一样

遍历字典中的所有键

方法keys()返回所有的键

lang={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
for name in lang.keys():
    print(name.title())
Jen
Sarah
Edward
Phil

遍历字典时默认遍历所有的键,所以keys()省略也可以
使用keys()确定某人是否接受了调查

lang={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
if 'erin' not in lang.keys():
    print("erin,please take our poll!")
erin,please take our poll!

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

用函数sorted()来获得按特定顺序排列的键列表的副本

lang={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
for name in sorted(lang.keys()):
    print(name.title()+" thank you!")
Edward thank you!
Jen thank you!
Phil thank you!
Sarah thank you!

遍历字典所有值

方法values()返回值列表

lang={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
print("the following language have been mentioned:")
for name in lang.values():
    print(name.title())
Python
C
Ruby
Python

set()函数可删除多余元素

lang={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
print("the following language have been mentioned:")
for name in set(lang.values()):
    print(name.title())
the following language have been mentioned:
Ruby
C
Python

嵌套

列表、字典相互套娃

字典列表

有三个外星人的字典信息,整合到一个列表中

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)
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

创建30个绿色外星人,显示前5个

aliens=[]
new_alien={'color':'green','points':'5','speed':'slow'}
for alien in range(30):
    aliens.append(new_alien)
for a in aliens[:5]:
    print(a)
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}

在字典中存储列表

pizza的一个属性可能有多个元素

pizza={
    'crust':'thick',
    'toppings':['mushrooms','extra cheese'],
    }
print("you order a "+pizza['crust']+" with:")
for top in pizza['toppings']:
    print("\t"+top)
you order a thick with:
        mushrooms
        extra cheese

“\t”表示缩进
每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表

lang={
    'jen':['python','ruby'],
    'sarah':['c'],
    'edward':['ruby','go'],
    'phil':['python','haskell'],
    }
for name,languages in lang.items():
    print("\n"+name.title()+"'s favirate languages are:")
    for language in languages:
        print("\t"+language.title())
Jen's favirate languages are:
        Python
        Ruby

Sarah's favirate languages are:
        C

Edward's favirate languages are:
        Ruby
        Go

Phil's favirate languages are:
        Python
        Haskell

在字典中存储字典

输出多个用户的多种属性

users={
    'jack':{
        'first':'albert',
        'last':'jack',
        'location':'princeton',
        },
    'bob':{
        'first':'marie',    
        'last':'bob',
        'location':'paris',
        },
    }
for username,userinfo in users.items():
    print("\nusersname: "+username)
    fullname=userinfo['first']+' '+userinfo['last']
    print("\tfullname: "+fullname.title())
    print("\tlocation: "+userinfo['location'].title())

usersname: jack
        fullname: Albert Jack
        location: Princeton

usersname: bob
        fullname: Marie Bob
        location: Paris
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值