python入门笔记(4)

字典
感觉字典相对于列表而言有了一个索引
1.定义
eg:alien_0 = { ‘color’: ‘green’, ‘points’: 5**}**

在字典alien_0中存储了外星人的颜色和点数。
跟列表不同的是用了“{}”;‘color’:'green’和‘points’:5称为键一值对。

2.访问字典:
在上述例子中打印
print(alien_0[‘color’])
输出:green

3.添加键一值对
在例子1中添加:
alien_0[‘x_position’] = 0
alien_0[‘y_position’] = 25
再打印出来:
print(alien_0)
输出:{‘color’:‘green’, ‘points’:5, ‘y_position’: 25, ‘x_position’:0}

4.修改字典的值
eg:alien_0 = {‘color’:‘green’}
alien_0[‘color’] = ‘yellow’
将绿色变成黄色

5.删除键一值对
eg:alien_0 = {‘color’: ‘green’, ‘points’: 5}
del alien_0[‘points’]

6.由类似对象组成的字典
eg:favorite_languages = {
‘jen’: ‘python’,
‘sarah’: ‘c’,
‘ebward’: ‘ruby’,
‘phil’: ‘python’,

7.遍历字典中所有的键
在6的基础上,

for name in favorite_languages.keys():
print(name.title())
输出:Edward
Jen
Phil
Sarah

8.遍历字典中所有的值
在6的基础上,

for language in favorite_languages.values():
print(language.title())
输出:Python
C
Ruby
Python
如果使用:
for language in set(favorite_languages.values()):
print(language.title())
则输出:Python
C
Ruby

如果要将键和值都遍历的话,可以试试这种方式:
eg: favorite_languages = {
‘jen’:[‘python’,‘ruby’],
‘sarah’:[‘c’],
‘edward’:[‘ruby’,‘go’],
‘phil’:[‘python’,‘haskell’],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + “'s favorite languages are:”)
for language in languages:
print("\t" + language.title())
输出:Jen’s favorite languages are:
Python
Ruby
Sarah’s favorite languages are:
C
Phil’s favorite languages are:
Python
Haskell
Edward’s favorite languages are:
Ruby

9.字典中存储列表
eg:pizza = {
‘crust’: ‘thick’,
’topping’:[‘mushrooms’, ‘extra cheese’],
}
for topping in pizza[‘toppings’]:
print("\t" + topping)
输出:mushrooms
extra cheese

10.字典中的字符转成整型
eg:age = input(“How old are you?”)
age = int(age)
age >=18

11.列表元素
增加:.pop(),append()
eg:
unconfirmed_users = [‘alice’,‘brain’,‘candace’]
confirmed_users = []
while unconfirmed_users:
current_users= unconfirmed_users.pop()
print(“verifying users:” + current_users.title())
confirmed_users.append(current_users)
for confirmed_user in confirmed_users:
print(confirmed_user.title()
删除:remove()
eg:
pets = [‘dog’,‘cat’,‘dog’,‘goldfish’,‘cat’,‘rabbit’,‘cat’]
print(pets)

while ‘cat’ in pets:
pets.remove(‘dog’)
print(pets)
关联:responses[name] = response
eg:
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat’s your name?")
response = input("\nWhich moutain do you like to climb someday?")
responses[name] = response
repeat = input("\nWould you like to let another person to respond?(yes/no)")
if repeat ==‘no’:
polling_active = False
print("\n—Polling Results—")
for name,response in responses.items():
print(name + " would you like to climb" + response + “.”)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值