Python Learning--Dictionary

Source: Internet
Author: User

Data structures that refer to values by name in Python are called mappings (mapping). Dictionaries are the only types of mappings in Python that are built in (the Python interpreter itself supports, and does not require import). The values in the dictionary are not in a special order and are stored under a specific key. A key can be a number, a string, or even a tuple.

First, create a dictionary

Phonebook = {'Tom':'1234','Lily' :'4567'}

The dictionary consists of two curly braces {}, which can be represented by an empty dictionary.

Separated by a colon ': ' between each key and its value. The key can be any immutable type

The items are separated by commas ', '.

The keys in the dictionary are unique, and the values are not unique. If there is an entry with the same key name, the following value overrides the previous one.

>>> a = {1:2,1:3,1:4,2:2}>>> a{1:4, 2:2}

Function Role
Dict () A sequence of CV dictionaries through other mappings or (key, value) pairs

Second, Basic dictionary operation

Operation Description
Len (d) Returns the number of items (key-value) in dictionary D
D[K] Returns the value associated to the key K
D[k] = V

Associate the value V to the key K

If K does not exist, a new item is created

Del D[k] Delete Item with key K
K in D Check if dictionary D contains an entry with a key of K

Iii. formatting strings for dictionaries

    1. >>> phonebook
    2. {‘Lily‘: ‘2345‘, ‘Tom‘: ‘1234‘}
    3. >>> "Tom‘s phone number is %(Tom)s." % phonebook
    4. "Tom‘s phone number is 1234."
After the% character in each conversion specifier, you can add a key (enclosed in parentheses), followed by another description element.

Four, the Dictionary method

Method Example Description
Dict.clear ()

>>> Phonebook

{' Lily ': ' 2345 ', ' Tom ': ' 1234 '}

>>> Phonebook.clear ()

>>> Phonebook

{}

Clears all the entries in the dictionary, with no return value (or none returned). This is an in-place operation where the original dictionary is manipulated directly.
Dict.copy ()

>>> x = {' A ': 1, ' B ': 2, ' C ': 3}

>>> y = x.copy ()

>>> y[' C ']=100

>>> y

{' A ': 1, ' C ': +, ' B ': 2}

>>> x

{' A ': 1, ' C ': 3, ' B ': 2}

Returns a new dictionary with the same key-value pairs.

But this method is shallow copy. The original dictionary is not affected when the value is substituted in the copy (the re-assignment in the example). But if you modify a value (not a replacement, a modification, such as a delete), the original dictionary will change.

Deepcopy (Dict) This is a deep copy, which is different from copy. When a new copy is obtained, the modification does not affect the original dictionary.
Dict.fromkeys ()

>>> x= {' ab ': ' 1 ', ' CD ': ' 2 '}

>>> X.fromkeys ([' EF ', ' gh '])

{' EF ': none, ' GH ': none}

>>> x

{' AB ': ' 1 ', ' CD ': ' 2 '}

>>> Y=x.fromkeys ([' EF ', ' gh '])

>>> y

{' EF ': none, ' GH ': none}

Creates a new dictionary with the given key, with each key corresponding to a default value of None.

Returns a new sequence.

can {}.fromkeys (...) or Dict.fromkeys (...)

Dict.get ()

>>> x

{' AB ': ' 1 ', ' CD ': ' 2 '}

>>> x.get (' CD ')

' 2 '

>>> x.get (' AA ')

>>> print x.get (' AA ')

None

>>> x.get (' AA ', ' N/A ')

' N/A '

The method that accesses the dictionary entry, if it does not exist, returns none. You can also define the return value when you cannot find it yourself.
Dict.has_key ()

>>> x

{' AB ': ' 1 ', ' CD ': ' 2 '}

>>> x.has_key (' AB ')

True

>>> x.has_key (' ax ')

False

Check if the dictionary contains a specific key.

This expression is equivalent to K in D

Dict.items ()

>>> x

{' AB ': ' 1 ', ' CD ': ' 2 '}

>>> X.items ()

[(' Ab ', ' 1 '), (' CD ', ' 2 ')]

Returns all entries for the dictionary as a list, with each item in the list represented as a (key, value) pair, but returned in no particular order.
Dict.iteritems ()

>>> x

{' AB ': ' 1 ', ' CD ': ' 2 '}

>>> it = X.iteritems ()

>>> List (IT)

[(' Ab ', ' 1 '), (' CD ', ' 2 ')]

Similar to the Ltems, but returns an iterator
Dict.keys ()

>>> x

{' AB ': ' 1 ', ' CD ': ' 2 '}

>>> X.keys ()

[' AB ', ' CD ']

Returns the key of the dictionary as a list
Dict.pop ()

>>> x

{' AB ': ' 1 ', ' CD ': ' 2 '}

>>> x.pop (' AB ')

' 1 '

>>> x

{' CD ': ' 2 '}

Gets the value corresponding to the given key, and then removes the key-value pair from the dictionary.
Dict.popitem ()

>>> x

{' GH ': ' 3 ', ' AB ': ' 1 ', ' CD ': ' 2 '}

>>> X.popitem ()

(' GH ', ' 3 ')

>>> x

{' AB ': ' 1 ', ' CD ': ' 2 '}

Functions like pop, just a random entry in the popup list.
dict.setdefault

>>> x

{' AB ' : ' 1 ', ' CD ': ' 2 '}

>>> print x.setdefault (' gh ')

None

>>> x

{' GH ': None, ' AB ': ' 1 ', ' CD ': ' 2 '}

>>> print x.setdefault (' ij ', ' n/a ')

N/a

>>> x

{' GH ': None, ' AB ': ' 1 ', ' ij ': ' N/A ', ' CD ': ' 2 '}

>>> x.setdefault (' ab ')

' 1 '

To some extent similar to the Get method.

When the key does not exist, SetDefault returns the default value and the corresponding update dictionary, the default value is optional, you can set the value yourself. If the key exists, it returns its corresponding value, but does not change the dictionary.

Dict.update ()

>>> y

{' mm ': ' Haha ', ' CD ': ' KK '}

>>> x

{' GH ': None, ' ab ': ' 1 ', ' ij ': ' N/A ', ' CD ': ' 2 '}

>>> x.update (y)

>>> x

{' AB ': ' 1 ', ' mm ': ' Haha ', ' CD ': ' KK ', ' ij ': ' N/a ', ' GH ': None}

Use a dictionary entry to update another dictionary. The items in the provided dictionary are added to the old dictionary, and if the same key is overwritten

D.values ()

>>> x

{' AB ': ' 1 ', ' mm ': ' Haha ', ' CD ': ' KK ', ' ij ': ' N/a ', ' GH ': None}

>>> x.values ()

[' 1 ', ' haha ', ' kk ', ' N/A ', None]

Returns a list of values in a dictionary that can contain duplicate elements in a list of returned values.

Clear's Special note:

The so-called direct operation of the original dictionary can be seen from the following two examples of comparison

Example 1:

>>> x={}

>>> y=x

>>> x[' key ']= ' value '

>>> y

{' key ': ' Value '}

>>> x={}

>>> y

{' key ': ' Value '}

Example 2:

>>> x={}

>>> y=x

>>> x[' key ']= ' value '

>>> y

{' key ': ' Value '}

>>> X.clear ()

>>> y

{}

From the above two examples, x, y initially corresponds to the same dictionary, example 1, by re-associating X to a new empty dictionary to achieve the purpose of emptying, there is no effect on Y. However, in Example 2, using the clear method to clear the elements in the original data will affect Y.

Python Learning--Dictionary

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.