Examples of Dictionary usage in python

Source: Internet
Author: User
This article mainly introduces the usage of the Dictionary (Dictionary) in python and provides detailed analysis of common operations such as creating, adding, and deleting a Python Dictionary in the form of an instance, for more information about the Dictionary usage in python, see the following example. Share it with you for your reference. The specific analysis is as follows:

A Dictionary is a data type of the ing structure. it is composed of unordered "key-value pairs. The dictionary key must be of unchangeable type, such as string, number, and tuple. The value can be of any python data type.

1. create a dictionary

>>> Dict1 ={}# create an empty dictionary >>> type (dict1)
 

2. add dictionary elements: two methods

>>> Dict1 ['A'] = 1 # First >>>> dict1 {'a': 1} # Second method: setdefault >>> dict1.setdefault ('B ', 2) 2 >>> dict1 {'a': 1, 'B': 2}

3. delete a dictionary

# Delete a specified key-value pair >>>> dict1 {'a': 1, 'B ': 2 }>>> del dict1 ['A'] # You can also use the pop method, dict1.pop ('A') >>>> dict1 {'B ': 2} # clear the dictionary >>> dict1.clear () >>> dict1 # DICTIONARY becomes empty {}# delete dictionary object >>> del dict1 >>> dict1Traceback (most recent call last): File"
 
  
", Line 1, in
  
   
NameError: name 'dict1' is not defined
  
 

4. dictionary method

1) get (key, default = None)

Returns the value corresponding to the key. if the key is not in the dictionary, the default value is returned. the default value is None.

>>> Dict1 # empty dictionary {}>> dict1.get ('A') # key 'A' does not exist in dict1, return none >>> dict1.get ('d1 ', 'no1') # The default parameter provides the value 'no1 ', so return 'no1' 'no1' >>> dict1 ['A'] = 'no1' # insert a new element >>>> dict1 {'a ': '000000' >>> dict1.get ('A') # The current key 'A' exists, and its value '20140901' is returned'

2) clear the dictionary

3) If has_key (key) appears in dict, True is returned; otherwise, False is returned.

>>> dict1{'a': '1111'}>>> dict1.has_key('b')False>>> dict1.has_key('a')True

4) items returns a list of dict (key, value) tuple pairs

>>> dict1{'a': 'no1', 'b': '2222'}>>> dict1.items()[('a', 'no1'), ('b', '2222')]

5) keys returns the dict key list

6) values returns the dict value list

>>> dict1{'a': 'no1', 'b': '2222'}>>> dict1.keys()['a', 'b']>>> dict1.values()['no1', '2222']

7) setdefault (key, default = None)

If a key exists in dict, the key value is returned. If no key is found, the key is added to dict. The value is given by the default parameter. the default value is None.

8) update (dict2)

Add the dict2 element to dict. when the key word is repeated, it overwrites the key value in dict.

>>> Dict2 {'C': '000000', 'B': 'no2 '} >>> dict1 # The Keys' B 'of dict2 and dict1 are repeated {'a ': 'no1', 'B': '000000'} >>> dict1.update (dict2) # After update is called, the key 'B' value of dict1 is overwritten >>> dict1 {'a': 'no1', 'C': '000000', 'B': 'no2 '}

9) popitem deletes any key-value pair and returns the key-value pair. if the dictionary is empty, an exception occurs.

>>> dict1{'b': 'no2'}>>> dict1.popitem()('b', 'no2')>>> dict1{}>>> dict1.popitem()Traceback (most recent call last): File "
 
  ", line 1, in 
  
   KeyError: 'popitem(): dictionary is empty'
  
 

10) pop (key, [d]) deletes the key-value pair of the specified key word and returns the value corresponding to the key.

>>> dict1{'a': 'no1', 'c': '3333', 'b': 'no2'}>>> dict1.pop('a')'no1'>>> dict1{'c': '3333', 'b': 'no2'}

11) copy returns a shortest copy of the dictionary.

I hope this article will help you with Python programming.

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.