Application details of the Python dictionary

Source: Internet
Author: User
I. dictionary creation method ①: & amp; gt; dict1 {}& amp; gt; & amp; gt; dict2 {name: earth, port: 80} & amp; gt; dict1, dict2 ({}, {port: 80, name: earth}) method ②: from Python2.2 & amp; gt; fdictdict ([x, 1], [1. create a dictionary

Method ①:
>>> Dict1 = {}
>>> Dict2 = {'name': 'Earth ', 'port': 80}
>>> Dict1 and dict2
({},{ 'Port': 80, 'name': 'global '})

Method 2: Start with Python 2.2
>>> Fdict = dict (['X', 1], ['y', 2])
>>> Fdict
{'Y': 2, 'x': 1}

Method ③:

From Python 2.3, you can use a convenient built-in method fromkeys () to create a "default" Dictionary, Word
The element in the code has the same value (if not given, the default value is None ):
>>> Ddict ={}. fromkeys ('X', 'y'),-1)
>>> Ddict
{'Y':-1, 'x':-1}
>>>
>>> Edict ={}. fromkeys ('foo', 'bar '))
>>> Edict
{'Foo': None, 'bar': None}

2. how to access values in the dictionary

① To traverse a dictionary (usually using a key), you only need to view its key cyclically, as shown in the following code:
>>> Dict2 = {'name': 'Earth ', 'port': 80}
>>>
>>>> For key in dict2.keys ():
... Print 'key = % s, value = % s' % (key, dict2 [key])
...
Key = name, value = earth
Key = port, value = 80

② Starting from Python 2.2
Traverse the dictionary in the for loop.
>>> Dict2 = {'name': 'Earth ', 'port': 80}
>>>
>>>> For key in dict2:
... Print 'key = % s, value = % s' % (key, dict2 [key])
...
Key = name, value = earth
Key = port, value = 80


To get the value of an element in the dictionary, you can use the dictionary key you are familiar with and brackets to get the value:
>>> Dict2 ['name']
'Global'
>>>
>>> Print 'host % s is running on port % d' % \
... (Dict2 ['name'], dict2 ['port'])
Host earth is running on port 80


③ Dictionary all methods. Methods has_key (), in, and not in are Boolean operators.
>>> 'Server' in dict2 # or dict2.has _ key ('server ')
False
>>> 'Name' in dict # or dict2.has _ key ('name ')
True
>>> Dict2 ['name']
'Global'
An example of mixing numbers and strings in a dictionary:
>>> Dict3 = {}
>>> Dict3 [1] = 'abc'
>>> Dict3 ['1'] = 3.14159
>>> Dict3 [3.2] = 'XYZ'
>>> Dict3
{3.2: 'XYZ', 1: 'ABC', '1': 3.14159}


3. update the dictionary

Update by overwriting
In the preceding example, dict2 ['name'] = 'global ';
Update dict2 ['name'] = 'abc ';

4. delete dictionary elements and dictionaries
Del dict2 ['name'] # Delete an entry whose key is "name"
Dict2.clear () # Delete all entries in dict2
Del dict2 # delete the entire dict2 Dictionary
Dict2.pop ('name') # Delete and return an entry whose key is "name"

Dict2 = {'name': 'Earth', 'port': 80}
>>> Dict2.keys ()
['Port', 'name']
>>>
>>> Dict2.values ()
[80, 'global']
>>>
>>> Dict2.items ()
[('Port', 80), ('name', 'global')]
>>>
>>> For eachKey in dict2.keys ():
... Print 'dict2 key', eachKey, 'has value', dict2 [eachKey]
...
Dict2 key port has value 80
Dict2 key name has value earth


The update () method can be used to add the content of a dictionary to another dictionary.

{'Server': 'http', 'port': 80, 'host': 'Venus '}
>>> Dict3.clear ()
>>> Dict3
>>> Dict3


V. functions related to ing types

>>> Dict (x = 1, y = 2)
{'Y': 2, 'x': 1}
>>> Dict8 = dict (x = 1, y = 2)
>>> Dict8
{'Y': 2, 'x': 1}
>>> Dict9 = dict (** dict8)
>>> Dict9
{'Y': 2, 'x': 1}

Dict9 = dict8.copy ()

Built-in Dictionary methods:

Dictionary key value: dict9.keys ()

Dictionary value: dict9.values ()

All dictionary items: dict9.items ()

Returned dictionary value: dict9.get ('Y ')

Table 7.2 Dictionary type method

Method name Operation

Dict. cleara () delete all elements in the dictionary

Dict. copya () returns a copy of the dictionary (light copy ).

Dict. fromkeysc (seq, val = None) c creates and returns a new dictionary, which uses the elements in seq as the dictionary key, val is the initial value corresponding to all keys in the dictionary. (if this value is not provided, the default value is None)

Dict. get (key, default = None) a pairs the key in the dictionary dict and returns its corresponding value. if this key does not exist in the dictionary, the default value is returned. (note, the default value is None)

Dict. has_key (key) if the key exists in the dictionary, True is returned; otherwise, False is returned. after the in and not in methods are introduced in Python2.2, this method is almost obsolete, but one
Workable interfaces.

Dict. items () returns a list of tuples containing Dictionary (key, value) pairs.

Dict. keys () returns a list containing the dictionary's Middle keys.

The dict. iter () d method iteritems (), iterkeys (), and itervalues () are the same as their non-iterative methods. The difference is that they return an iterator instead of a list.

Dict. popc (key [, default]) c is similar to the get () method. if the key in the dictionary exists, delete it and return the dict [key]. if the key does not exist, the default value is not provided, causing a KeyError.

Dict. setdefault (key, default = None) e is similar to the method set (). if the key does not exist in the dictionary, dict [key] = default assigns a value to it.

Dict. update (dict2) a adds the key-value pair of the dictionary dict2 to the dictionary dict

Dict. values () returns a list containing all values in the dictionary.

① (3) (4) (6) (7)
VI. set type
① Set () and frozenset () using the factory method of the set ():
>>> S = set ('cheeseshop ')
>>> S
Set (['C', 'e', 'H', 'O', 'P', 's'])
>>> T = frozenset ('bookshop ')
>>> T
Frozenset (['B', 'H', 'K', 'O', 'P', 's'])
>>> Type (s)

>>> Type (t)


② How to update a set
Add and delete members of a set using built-in methods and operators of various sets:
>>> S. add ('Z ')
>>> S
Set (['C', 'e', 'H', 'O', 'P', 'S', 'Z'])
>>> S. update ('pypi ')
>>> S
Set (['C', 'e', 'I', 'H', 'O', 'P', 'S', 'y', 'Z'])
>>> S. remove ('Z ')
>>> S
Set (['C', 'e', 'I', 'H', 'O', 'P', 'S', 'y'])
>>> S-= set ('pypi ')
>>> S
Set (['C', 'e', 'H', 'O', 's'])

③ Delete a set
Del s

④ Member relationship (in, not in)
>>> S = set ('cheeseshop ')
>>> T = frozenset ('bookshop ')
>>> 'K' in s
False
>>> 'K' in t
True
>>> 'C' not in t
True

⑤ Set equivalence/non-equivalence
>>> S = t
False
>>> S! = T
True
>>> U = frozenset (s)
>>> S = u
True
>>> Set ('posh') = set ('shop ')
True

⑥ Difference supplement/relative supplement set (-)
The difference or relative supplement set of two sets (s and t) refers to a set C. The elements in the set belong to only the set s, not
In set t. The difference symbol has an equivalent method, difference ().
>>> S-t
Set (['C', 'E'])

Symmetric difference (^): symmetric difference is the XOR of a set.

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.