A detailed description of the Python dictionary application

Source: Internet
Author: User
I. Creating a dictionary

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

Method ②: From Python version 2.2
>>> fdict = Dict ([' X ', 1], [' Y ', 2])
>>> fdict
{' Y ': 2, ' X ': 1}

Method ③:

From the Python 2.3 version, you can create a "default" dictionary with a handy built-in method, Fromkeys ()
The element in the code has the same value (none by default if not given):
>>> ddict = {}.fromkeys (' x ', ' Y '),-1)
>>> ddict
{' Y ':-1, ' X ':-1}
>>>
>>> edict = {}.fromkeys (' foo ', ' Bar ')
>>> Edict
{' Foo ': None, ' Bar ': none}

Two. How to access values in a dictionary

① to traverse a dictionary (usually with a key), you just need to loop through its keys, like this:
>>> 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 in parentheses to get:
>>> dict2[' name ']
' Earth '
>>>
>>> print ' host%s ' running on port%d '% \
... (dict2[' name '], dict2[' Port ')
Host Earth is running on port 80


③ Dictionary all the methods. The Has_key () and in and not-in operators are all Boolean types.
>>> ' server ' in Dict2 # or Dict2.has_key (' server ')
False
>>> ' name ' in Dict # or Dict2.has_key (' name ')
True
>>> dict2[' name ']
' Earth '
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}


Three. Updating dictionaries

Take an overlay update
In the example above dict2[' name ']= ' earth ';
Updated dict2[' name ']= ' abc ';

Four. Delete dictionary elements and dictionaries
Del dict2[' name ' # Delete entry with key ' name '
Dict2.clear () # Delete all entries in Dict2
Del Dict2 # Delete entire Dict2 dictionary
Dict2.pop (' name ') # Delete and return an entry with the key "name"

Dict2 = {' name ': ' Earth ', ' Port ': 80}
>>> Dict2.keys ()
[' Port ', ' name ']
>>>
>>> dict2.values ()
[The earth ']
>>>
>>> Dict2.items ()
[(' Port ', '), (' Name ', ' Earth ')]
>>>
>>> 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 contents of a dictionary to another dictionary

{' server ': ' http ', ' Port ': $, ' host ': ' Venus '}
>>> Dict3.clear ()
>>> Dict3
>>> Dict3


Five. Mapping type-related functions

>>> 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 ()

Dictionary built-in methods:

Dictionary key value: Dict9.keys ()

Dictionary value: Dict9.values ()

Dictionary All items: Dict9.items ()

Return dictionary value: Dict9.get (' y ')

Table 7.2 Dictionary Type methods

Method name Operation

Dict.cleara () Delete all the elements in the dictionary

Dict.copya () Returns a copy of the dictionary (shallow copy)

DICT.FROMKEYSC (Seq,val=none) C creates and returns a new dictionary that is the key to the dictionary in the SEQ element, and Val does the initial value for all the keys in the dictionary (default is None if this value is not provided)

Dict.get (Key,default=none) A pairs the key in the dictionary dict, returns the value it corresponds to, and returns the value of default if the key does not exist in the dictionary (note that the default value of the parameter is None)

Dict.has_key (Key) returns True if the key (key) exists in the dictionary, otherwise false is returned. After the Python2.2 version introduced in and not, this method is almost obsolete, but it still provides a
The interface that can work.

Dict.items () Returns a list containing the tuple (key, value) in the dictionary

Dict.keys () Returns a list containing the keys in the dictionary

The Dict.iter () d method Iteritems (), Iterkeys (), and itervalues () are the same as the non-iterative methods they correspond to, but they return an iteration instead of a list.

DICT.POPC (key[, default]) C and method get () similar, if the dictionary key key exists, delete and return Dict[key], if the key key does not exist, and does not give the value of default, throws a Keyerror exception.

Dict.setdefault (Key,default=none) e is similar to method set (), and is assigned a value by Dict[key]=default if the key key is not present in the dictionary.

Dict.update (DICT2) A adds the key-value pairs of the dictionary dict2 to the dictionary dict

Dict.values () Returns a list that contains all the values in the dictionary

①②③④⑤⑥⑦⑧⑨⑩
Six. Collection type
① with Set factory method set () and Frozenset ():
>>> 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 ' Set ' >
>>> type (t)
<type ' Frozenset ' >

② How to update a collection
Add and remove members of a collection with various set of built-in methods and operators:
>>> 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 '])

③ Deleting a collection
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/not equivalent
>>> s = = t
False
>>> s! = t
True
>>> u = frozenset (s)
>>> s = = u
True
>>> set (' posh ') = = set (' Shop ')
True

⑥ differential/relative complement set (–)
The difference complement or relative complement of two sets (S and T) refers to a set of C, the elements of the set that belong to the set S only, not
to the collection T. The difference symbol has an equivalent method, difference ().
>>> s-t
Set ([' C ', ' e '])

Symmetric difference (^): Symmetric difference is an XOR of a set
  • Related Article

    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.