Python core Programming Read Pen 5: Mappings and collection types

Source: Internet
Author: User

Seventh chapter mapping and aggregation capabilities

A dictionary (the only mapping type in Python)

1 basic

Create and assign values:

Normal creation: >>>dict = {' name ': ' Earth ', ' Port ': 80}

Use the Factory function Dict () to create:

>>> fdict = Dict ([' X ', 1], [' Y ', 2])
>>> fdict
{' Y ': 2, ' X ': 1}
Use Fromkeys () to create a default dictionary:

>>> ddict = {}.fromkeys (' x ', ' Y '),-1)
>>> ddict
{' Y ':-1, ' X ':-1}

>>> edict = {}.fromkeys (' foo ', ' Bar ')
>>> Edict
{' Foo ': None, ' Bar ': none}
  

To access the values in the dictionary:

dict[' name ']

    

>>>> for key in Dict2. Keys():
... print ' key=%s, value=%s '% (key, Dict2[key])

>>>> for key in Dict2:
... print ' key=%s, value=%s '% (key, Dict2[key])

Has_key () and in, not to determine if a key is in the dictionary

  

To delete a dictionary element and dictionary:

Del dict[' name ']

Dict.clear ()

Del Dict

Dict.pop (' name ') deletes and returns an entry with the key ' name '

      

2 operator

Python core Programming Read Pen 5: Mappings and collection types

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.