Python dictionary operations Detailed (create, access, delete)

Source: Internet
Author: User
Tags shallow copy

Let's take a look at the dictionary built-in method

Method Name Operation
Dict.clear () Delete all elements in a dictionary
Dict.copy () Returns a copy of a dictionary (shallow copy)
DICT.FROMKEYSC (Seq,val=none) Creates and returns a new dictionary, which is the key of the dictionary in Seq, and Val does the initial value for all keys in the dictionary (none is default if this value is not provided)
Dict.get (Key,default=none) Returns the value of the key in the dictionary dict, and returns the value of default if this key is not present in the dictionary (note that the default value for parameter default is None)
Dict.has_key (Key) Returns true if the key is present in the dictionary, or false. After the Python2.2 version is introduced in and not, this method is almost obsolete, but still provides a working interface.
Dict.items () Returns a list containing the dictionary (key, value) to tuple
Dict.keys () Returns a list containing the keys in the dictionary
Dict.values () Returns a list containing all the values in the dictionary
Dict.iter () Methods Iteritems (), Iterkeys (), itervalues () are the same as their corresponding non iterative methods, but they return an iteration rather than a list.
Dict.pop (key[, default]) Similar to the method get (), if the key key in the dictionary exists, deletes and returns Dict[key], and throws a Keyerror exception if the key does not exist and the value of default is not given.
Dict.setdefault (Key,default=none) Similar to the method set (), if the key is not present in the dictionary, it is assigned a value by Dict[key]=default.
Dict.setdefault (Key,default=none) Similar to the method set (), if the key is not present in the dictionary, it is assigned a value by Dict[key]=default.

Tuples are generally expressed in parentheses, such as (1,2,3)
Lists are generally expressed in square brackets, such as [1,2,3]

The dictionary (dict) is represented by curly braces, such as {' A ': 1, ' B ': 2, ' C ': 3}
Unlike PHP, PHP's key,value are represented by Key=>value, and Python is separated by a colon ":".

Dictionaries can use curly braces to write keys and values or use the Dict function to create them.
The Dict function can specify two tuples or lists to correspond to the creation of a dictionary. Such as:

Items = [(' Name ', ' Gumby '), (' Age ', ' 42 ')]
D = dict (items)

The difference from the list:

K in D (d is a dictionary), looking for a key instead of value, and the expression V in L (L is a list) is used to find the value, not the index.

Some dictionary methods:

Clear clears the dictionary. "In-place operation" does not return a value, similar to the list's Sort method
The Copy method returns a new dictionary of the same key-value pairs. Shallow copy. Because the value itself is the same, not the replica.
When you replace a value in a replica, the original dictionary is unaffected. But if you modify a value, the original dictionary changes. One way to avoid this problem is to use deep copy (deep copy).
From copy import deepcopy
Deepcopy (d)

The D.fromkes method creates a new dictionary with the given value. The default for each key corresponds to none
The Get method gets a nonexistent key without an error and returns none
Has_key method Phase method in expression K-D
The items method returns all the alphabetic items as a list. Each of these lists comes from (the key, the value). However, items do not have a special order when they are returned.
The Iteritmes method is roughly the same, but returns an iterator object instead of a list. In many cases iteritems efficiency is higher. An iterator, which is equivalent to an object after decode JSON, rather than an array,
The Keys method returns the key in the dictionary as a list. Iterkeys, however, returns an iterator for the key.
Pop pops up the value of the given key. Popitem pops up the last element (actually a random item), but if you want to remove and process the dictionary one after another, the popitem is much more efficient because you don't have to get a list of the dictionary's key values first.

Values and Itervalues methods return a value in a dictionary as a list or iterator, and the list of returned values can contain duplicates.

Create

Method One:

The code is as follows Copy Code
>>> Dict1 = {}
>>> dict2 = {' name ': ' Earth ', ' Port ': 80}
>>> Dict1, Dict2
({}, {' Port ': ' Name ': ' Earth '})

Method Two: From the Python version 2.2, you can use a factory method to pass in an element that is a tuple of a list as an argument

The code is as follows Copy Code
>>> fdict = Dict ([' X ', 1], [' Y ', 2])
>>> fdict
{' Y ': 2, ' X ': 1}

Method Three:

From the Python 2.3 release, you can create a "default" dictionary with a handy built-in method Fromkeys () that has the same value in the dictionary (if not given, default to None, which is a bit like the Oneobject method of my frame):

The code is as follows Copy Code
>>> ddict = {}.fromkeys (' x ', ' Y '),-1)
>>> ddict
{' Y ':-1, ' X ':-1}
>>>
>>> edict = {}.fromkeys (' foo ', ' Bar ')
>>> Edict
{' Foo ': None, ' Bar ': none}

Accessing values in a dictionary

To traverse a dictionary (the General key), you only need to loop through its keys, like this:

The code is as follows Copy 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 with Python 2.2, you can iterate through the dictionary directly in the For loop.

The code is as follows Copy Code
>>> 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 determine if there is a key-value pair, you can use the Has_key () or in and not in operators

The code is as follows Copy Code
>>> ' server ' in Dict2 # or Dict2.has_key (' server ')
False
>>> ' name ' in Dict # or Dict2.has_key (' name ')
True
>>> dict2[' name ']
' Earth '

Examples of mixing numbers and strings in a dictionary:

The code is as follows Copy Code
>>> dict3 = {}
>>> dict3[1] = ' abc '
>>> dict3[' 1 '] = 3.14159
>>> dict3[3.2] = ' xyz '
>>> Dict3
{3.2: ' xyz ', 1: ' abc ', ' 1 ': 3.14159}

Update dictionary

Take cover update

In the example above dict2[' name ']= ' earth ';

Update dict2[' name ']= ' abc ';
Delete dictionary elements and dictionaries

The code is as follows Copy Code

Del dict2[' name '] # Delete entry with key ' name '

Dict2.clear () # Delete all entries in the Dict2

Del Dict2 # Delete the entire dict2 dictionary

Dict2.pop (' name ') # deletes and returns an entry with the key ' name '
Dict2 = {' name ': ' Earth ', ' Port ': 80}
>>> Dict2.keys ()
[' Port ', ' name ']
>>>
>>> dict2.values ()
[, ' 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

The code is as follows Copy Code
DICT3 = {' server ': ' http ', ' Port ': #, ' Host ': ' Venus '}
>>> Dict3.clear ()
>>> Dict3
{}

mapping type-related functions

  code is as follows copy code
>>> 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 ()
/td>
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.