天天看點

Python chapter 6 learning notes

版權聲明:本文為部落客原創文章,原文均發表自http://www.yushuai.me。未經允許,禁止轉載。 https://blog.csdn.net/davidcheungchina/article/details/78243681

  A simple dictionary

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,

alien_0 

=

{

'color'

'green'

,

'point'

5

}

print

(alien_0[

'color'

])

alien_0[

'x_position'

=

alien_0[

'y_position'

=

25

print

(alien_0)

The window will show

{

'color'

'green'

'point'

5

'x_position'

'y_position'

25

}

    • Modify the key-value pair

alien_0[

'color'

=

'yellow'

    • Delete the key-value pair

Use del is OK.

del

alien_0[

'points'

]

Dictionary will not include points.

    • Dictionary just like struct in C language.
    • The dictionary which consists of many objects:

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,

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

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,

for

language 

in

set

(favorite_languages.values()):

print

(language.title())

n  Nesting: 将一系列字典存儲在清單中,或将清單作為值存儲在字典中,這被稱為嵌套。