Basic python tutorial-detailed explanation of dictionary operations

Source: Internet
Author: User
This article describes how to use the dictionary in python. For more information, see the dictionary.
Dictionary

1. Set of key-value pairs (map)

2. The dictionary is a set of data surrounded by braces "{}".

3. The dictionary is unordered and members are accessed by keys in the dictionary. Variable, nested, and can be modified and extended in the original place without generating a new dictionary

4. dictionary keys, which can be strings (case sensitive), numeric constants, or tuples (immutable types). Keys of the same dictionary can be mixed. The dictionary key must be Hash-able.

The condition for using tuples as keys is that the values in the element group are of an unchangeable type.

The Code is as follows:


A = (1, 2) # It can be used as a key
B = (1, 2, [3, 4]) # No

5. The dictionary value can be of any type, can be nested, and can be freely modified

Statement
Several ways to create a dictionary:

1. Basic

The Code is as follows:


D = {}# empty dictionary
D = {'name': 'Tom ', 'age': 22}
# Equivalence
D = {}
D ['name'] = 'Tom'
D ['age'] = 22

2. dict

The Code is as follows:


D = dict () # null
D = dict (name = 'Tom ', age = 22)

D = dict ([('name', 'Tom '), ('age', 22)])
# Equivalence
Keys = ['name', 'age']
Values = ['Tom ', 22]
D = dict (zip (keys, values ))

3. fromkeys

If default_value is not specified, the default value is None.

The Code is as follows:


>>> Dict. fromkeys (['name', 'age'], 'default _ value ')
{'Age': 'default _ value', 'name': 'default _ value '}

Basic operations

0. Get help

The Code is as follows:


Help (dict)


1. Determine whether the key exists in the dictionary

The Code is as follows:


If k in d: # k not in
Dosomething ()

2. Read

The Code is as follows:


D = {'A': 1, 'B': 2}
Print d ['a'] # returns 1. If the key does not exist, an exception KeyError is thrown. Use it with caution. We recommend that you do not use it.


Print d. get ('C', 3) # get 3. get method. If the key does not exist, return the second default_value. If no default_value is set, return None.
Three methods are provided to handle missing-key errors.

The Code is as follows:


If k in d:
Print d [k]

Try:
Print d [k]
Failed t KeyError:
Dosomething ()

Print d. get (k, default)
# Equivalent d [k] if k in d else default

3. Traverse

Method 1:

The Code is as follows:


For key in d:
Print key, d [key]
# Equivalent for key in d. keys ()

Method 2:

The Code is as follows:


For key, value in d. items ():
Print key, value

4. Modification Method 1: a key-Value Pair

The Code is as follows:


D ['key'] = 'newvalue'

Method 2: Batch add or update

The Code is as follows:


# Another dictionary
D. update ({'key': 'newvalue'}) # A group of values is supported.

# List of tuples
D. update ([('A', 1), ('B', 2)]) # two elements of each tuples, (key, value)

# ** Key
D. update (c = 3, e = 4)

5. Delete

The Code is as follows:


Del d ['key']
Value = d. pop ('key') # Delete and return values
D. clear () # clear
6. Others:

Len (d) # Length
D. keys () # key List
D. values () # value List
D. items () # (key, value) List
C = d. copy () # Light copy
# Return iterator, saving memory
D. iterkeys ()
D. itervalues ()
D. iteritems ()
D. setdefault ('name', 'ken') # If not, set it. Otherwise, the original value remains unchanged.

Others
1. Sort dictionaries by key

The Code is as follows:


Keys = d. keys ()
Keys. sort ()
For key in keys:
Print d. get (key)

Sort by value

The Code is as follows:


Sorted (d. items (), lambda x, y: cmp (x [1], y [1])


In addition:

The Code is as follows:


# Assume that d is a dictionary.
Sorted (d) # returns the same as sorted (d. keys (), and returns the key sort.

2. Use the custom object as the key

Required:

The Code is as follows:


Def _ hash _ (self ):
Pass
Def _ eq _ (self, other ):
Pass

3. Copy the dictionary in a shortest:

The Code is as follows:


C = d. copy ()#


The copy module must be used for deep copy.

The Code is as follows:


Form copy import deepcopy
C = deepcopy (d)

4. Assume that there is a large list l in one application scenario, and assume that there are 10 million records.

There is a small list of B, to determine whether the elements in B are in l

If:

The Code is as follows:


For I in B:
If I in l:
Dosomething ()

You will find that it is very slow... because the second in statement will traverse 10 million ....

Improvement:

The Code is as follows:


D = dict. fromkeys (l)
For I in B:
If I in d:
Dosomething ()
# Space change time, O (n)-> O (1)

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.