Python Introduction to the dictionary _python

Source: Internet
Author: User
Tags delete key shallow copy

A dictionary consists of a pair of keys and their corresponding values (a key value pair becomes an item), separated by a colon (:) between each key and its value, separated by commas (,), and the entire dictionary enclosed by a pair of curly braces. An empty dictionary consists of two curly braces: {}

dict function

You can use the Dict function to create a dictionary by using a sequence of other mappings or (keys, values)

Copy Code code as follows:

>>> items=[(' name ', ' Gumby '), (' Age ', 42)]
>>> d=dict (items)
>>> D
{' Age ':, ' name ': ' Gumby '}
>>> d[' name ']
' Gumby '

The Dict function can also create a dictionary by using keyword parameters:

Copy Code code as follows:

>>> d=dict (name= ' Gumby ', age=42)
>>> D
{' Age ':, ' name ': ' Gumby '}

Basic Dictionary operations:

The basic behavior of a dictionary resembles a sequence in many ways:
Len (d) Returns the number of items (key-value pairs) in D
D[K] Returns the value associated with the key K
D[k]=v to associate the value V on the key K
Del D[k] Delete key to K
K in D check if D contains keys to K
Description

Key type: The key of the dictionary is not necessarily integer data, or it may be other immutable types

Auto Add: Even if the key doesn't exist in the dictionary, it can be assigned a value so that the dictionary creates a new item and cannot associate the value to an index outside the list range

Membership: The expression K in D (d is a dictionary) looks for the key, not the value. Expression V in L (l for list) is used to find values, not indexes

Dictionary method:

1. Clear

The clear method clears all the entries in the dictionary, which is in-situ, so there is no return value

Copy Code code as follows:

>>> d={}
>>> d[' name ']= ' Gumby '
>>> d[' age ']=42
>>> D
{' Age ':, ' name ': ' Gumby '}
>>> Return_value=d.clear ()
>>> D
{}
>>> Print Return_value
None

Consider the following two types of situations:

Copy Code code as follows:

>>> x={}
>>> y=x
>>> x[' key ']= ' value '
>>> y
{' key ': ' Value '}
>>> x={}
>>> y
{' key ': ' Value '}
>>>
>>> x={}
>>> y=x
>>> x[' key ']= ' value '
>>> y
{' key ': ' Value '}
>>> X.clear ()
>>> y
{}

2, copy

The Copy method returns a new dictionary with the same key-value pair (this method implements a shallow copy)

Copy Code code as follows:

>>> x={' username ': ' admin ', ' machines ': [' foo ', ' Bar ', ' Baz ']}
>>> y=x.copy ()
>>> y[' username ']= ' MLH '
>>> y[' machines '].remove (' bar ')
>>> y
{' username ': ' MLH ', ' Machines ': [' foo ', ' Baz ']}
>>> x
{' username ': ' admin ', ' machines ': [' foo ', ' Baz ']}

As you can see from the code above, the original dictionary is not affected when you replace the value in the copy, but if you modify a value, the original dictionary changes

One way to avoid this problem is to use deep replication to copy all of the values it contains, and you can use the Deepcopy function of the copy module to do the following:

Copy Code code as follows:

>>> from copy import deepcopy
>>> d={}
>>> d[' names ']=[' Alfred ', ' Bertrand ']
>>> c=d.copy ()
>>> Dc=deepcopy (d)
>>> d[' names '].append (' Clive ')
>>> C
{' names ': [' Alfred ', ' Bertrand ', ' Clive ']}
>>> DC
{' names ': [' Alfred ', ' Bertrand ']}

3, Fromkeys

The Fromkeys method creates a new dictionary with the given key, with the default corresponding value of None for each key

Copy Code code as follows:

>>> {}.fromkeys ([' Nmae ', ' age '])
{' Age ': none, ' Nmae ': none}

4, get

The Get method is a more relaxed way to access a dictionary entry. In general, an error occurs when you try to access an item that does not exist in the dictionary:

Copy Code code as follows:

>>> d={}
>>> print d[' name '

Traceback (most recent call last):
File "<pyshell#77>", line 1, in <module>
Print d[' name '
Keyerror: ' Name '
>>> print d.get (' name ')

Using Get does not

Example of a simple database using get

Copy Code code as follows:

people={
' Alice ': {
' Phone ': ' 2341 ',
' Add ': ' Foo drive 23 '
},
' Beth ': {
' Phone ': ' 934 ',
' Add ': ' Bar Street 42 '
},
' Cecil ': {
' Phone ': ' 2314 ',
' Add ': ' Baz Avenue 90 '
}
}
labels={
' Phone ': ' Phone number ',
' Addr ': ' Address '
}
Name=raw_input (' Name: ')

#查询电话号码还是地址?
Request=raw_input (' Phone number (p) or address (a)? ')

#使用正确的键:
Key=request
If request== ' P ': key= ' phone '
If request== ' a ': key= ' addr '

Person=people.get (name,{})
Label=labels.get (Key,key)
Result=person.get (Key, ' not available ')

print '%s ' s%s is%s.% (Name,label,result)

>>> ================================ Restart ================================
>>>
Name:gumby
Phone number (p) or address (a)? Batting average
Gumby ' s batting average is not available.

5, Has_key

The Has_key method can check whether the dictionary contains the given key, and the expression D.has_key (k) corresponds to the expression K in D

Copy Code code as follows:

>>> d={}
>>> d.has_key (' name ')
False
>>> d[' name ']= ' Eric '
>>> d.has_key (' name ')
True

6. Items and Iteritems

The items method returns all the dictionary entries as a list, each of which comes from (a key, a value), but the item does not have a special order when it returns

Copy Code code as follows:

>>> d={' title ': ' Python Web Site ', ' url ': ' http://www.python.org ', ' spam ': 0}
>>> D.items ()
[' url ', ' http://www.python.org '], (' spam ', 0), (' title ', ' Python Web Site ')]

The Iteritems method works roughly the same, but returns an iterator object instead of a list:

Copy Code code as follows:

>>> It=d.iteritems ()
>>> it
<dictionary-itemiterator Object at 0x0280f6f0>
>>> List (IT)
[' url ', ' http://www.python.org '], (' spam ', 0), (' title ', ' Python Web Site ')]

7, Pop

The Pop method is used to obtain the value corresponding to the given key and then removes the key-value pair from the dictionary

Copy Code code as follows:

>>> d={' x ': 1, ' Y ': 2}
>>> d.pop (' x ')
1
>>> D
{' Y ': 2}

8, Popitem

The Popitem method is similar to List.pop, which pops up the last element of the list. But Popitem pops up random items.

Copy Code code as follows:

>>> d={' title ': ' Python Web Site ', ' url ': ' http://www.python.org ', ' spam ': 0}
>>> D
{' URL ': ' http://www.python.org ', ' spam ': 0, ' title ': ' Python Web Site '}
>>> D.popitem ()
(' url ', ' http://www.python.org ')
>>> D
{' spam ': 0, ' title ': ' Python Web Site '}

9, SetDefault

The SetDefault method is somewhat similar to a Get method, except that SetDefault can set the corresponding key value without the given key in the dictionary.

Copy Code code as follows:

>>> d={}
>>> d.setdefault (' name ', ' N/A ')
' N/A '
>>> D
{' name ': ' N/A '}
>>> d[' name ']= ' Gumby '
>>> d.setdefault (' name ', ' N/A ')
' Gumby '
>>> D
{' name ': ' Gumby '}

10, update

The Update method can update another dictionary with one dictionary item:

Copy Code code as follows:

>>> d={
' title ': ' Python Web Site ',
' URL ': ' http://www.python.org ',
' Changed ': ' Mar 22:09:15 MET 2008 '
}
>>> x={' title ': ' Python Langue Website '}
>>> d.update (x)
>>> D
{' URL ': ' http://www.python.org ', ' changed ': ' Mar 22:09:15 MET 2008 ', ' title ': ' Python Langue Website '}

11. Values and Itervalues

The values method returns the value in the dictionary as a list (the iterator for the returned value), unlike the list of return keys, which can contain duplicate elements in the list of itervalues:

Copy Code code as follows:

>>> d={}
>>> d[1]=1
>>> d[2]=2
>>> d[3]=3
>>> d[4]=1
>>> d.values ()
[1, 2, 3, 1]

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.