Python chapter 6 learning notes

  A simple dictionary

1
2
alien_0  =  { 'color' 'green' , 'point' 5 }
print (alien_0[ 'color' ]) #使用大括号

The window will show green.

l  Using dictionary

n  Add key-value pair

For example,

1
2
3
4
5
6
alien_0  =  { 'color' 'green' , 'point' 5 }
print (alien_0[ 'color' ])
  
alien_0[ 'x_position' =  0
alien_0[ 'y_position' =  25
print (alien_0)

The window will show

1
{ 'color' 'green' 'point' 5 'x_position' 0 'y_position' 25 }
    • Modify the key-value pair

1
alien_0[ 'color' =  'yellow'
    • Delete the key-value pair

Use del is OK.

For example,

1
del  alien_0[ 'points' ]

Dictionary will not include points.

    • Dictionary just like struct in C language.

    • The dictionary which consists of many objects:

For example,

1
2
3
4
5
6
7
8
9
10
favorite_languages  =  {
'David' 'python' ,
'Jane'  'java' ,
'John'  'C' ,
'Sarah'  'ruby' ,
'Michel'  'swift' 
}
  
print ( "David's favorite languages is "  + 
favorite_languages[ 'David' ].title()  +  "." )

It will show,

1
David's favorite languages  is  Python.

Remember the format!

l  Ergodic dictionary

n  Ergodic all key-value pairs

Method: items(): items()方法用于返回字典dict的(key,value)元组对的列表

    • Ergodic all keys

Method: keys():返回字典dict的键列表

For example,

1
2
3
4
5
for  name  in  favorite_languages.keys():
print (name.title()  +   "." )
But  if  we use
for  name  in  favorite_languages:
print (name.title()  +   "." )

They all have same output.

n  Ergodic all values

n  Method: values():返回字典dict的值列表

As we all know, the list of value may have same values, then ,how to keep only one value?

We can use set(). For example,

1
2
for  language  in  set (favorite_languages.values()):
print (language.title())

n  Nesting: 将一系列字典存储在列表中,或将列表作为值存储在字典中,这被称为嵌套。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值