PYTHON-10 Dictionary

Source: Internet
Author: User

#1 Create

dict1={' Huan Huan ': ' I love ', ' small high ': ' You '}

Dict2={1: ' One ', 2: ' Both ', 3: ' Three '}

dict3={}

#2 Access elements

Print (' Huanhuan: ', dict1[' Huan Huan ')

  Huan Huan: I love

Print (dict2[1])

  One

Print (DICT3)

  {}

#3 dict (Create Dictionary), key (gets all the keys in the specified dictionary), values (gets all the values in the specified dictionary), items (gets all the items in the specified dictionary: key + value)

Dict4=dict ((' A ', +), (' B ', ())) #创建1

Print (DICT4)

  {' A ': +, ' B ': 66}

Dict5=dict (a=65,b=66) #创建2

Print (DICT5)

  {' A ': +, ' B ': 66}

Dict6=dict.fromkeys ((), ' I love ') #创建3
Print (DICT6)

  {1: ' I Love ', 2: ' I love '}

Dict7=dict.fromkeys (Range (32), ' Huan Huan ')

For I in Dict7.keys (): #获取指定字典中所有的键
Print (i)
For I in Dict7.values (): #获取指定字典中所有的值
Print (i)
For I in Dict7.items (): #获取指定字典中所有的项: Key + value
Print (i)

#4 Get, SetDefault

Print (Dict7.get (32, ' none ')) #查找指定字典中键为32所对应的值 (returns ' None ' if no key 32)
Print (Dict7.setdefault) #查找指定字典中键为33所对应的值 (automatically add key 33 and its value ' 33 ' if no key 32)

#5 Pre-copy: Copy empty dictionary: Clear

Dict8=dict7

Dict9=dict7.copy ()

Print (ID (DICT7))
Print (ID (DICT8))
Print (ID (DICT9))

  54405320
54405320
49806392

Dict7.clear () #清空字典

#6 Pop, Popitem, update

Print (Dict7.pop (1)) #弹出指定键对应的值
Print (Dict7.popitem ()) #随机弹出一项: Key + value

Dict10={1:11}
Dict7.update (dict10) #利用字典dict10更新其他字典dict7

PYTHON-10 Dictionary

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.