Dictionary in Python

Source: Internet
Author: User

Dictionary in Python

The field is the only key-value type in the dictionary in Python. It is a very important data structure in Python. because it uses hash to store data, its complexity is O (1 ), fast. The following lists the common usage of dictionaries.

List of common dictionary Methods]

 

# Method # description D. clear () # Remove all items in D. copy () # returns the copy of D. fromkeys (seq [, val]) # returns the dictionary of keys obtained from seq and values set to val. Class method call D. get (key [, default]) # If D [key] exists, return it; otherwise, return the given default value NoneD. has_key (key) # Check whether D has a given key keyD. items () # Return the list of (Key, value) pairs that represent item D. iteritems () # from D. the (Key, value) pair returned by items () returns an iteratable Object D. iterkeys () # Return an iteratable Object D from the D key. itervalues () # Return an iteratable Object D from the value of D. keys () # returns the list of keys D. pop (key [, d]) # Remove and return the value D corresponding to the given key or given default value D. popitem () # Remove any item from D and use it as a (Key, value) pair to return D. setdefault (key [, default]) # If D [key] exists, return it; otherwise, return the default value NoneD. update (other) # add each item in other to D. D. values () # returns the list of values in D.
Five ways to create a dictionary]

 

Method 1: General Method# This method is more convenient if you can spell out the entire dictionary in advance

>>> D1 = {'name':'Bob','age':40}
Method 2: Dynamic Creation# This method is convenient if you need to dynamically create a dictionary Field
>>> D2 = {}>>> D2['name'] = 'Bob'>>> D2['age']  =  40>>> D2{'age': 40, 'name': 'Bob'}
Method 3: Dict-Keyword format# The code is relatively small, but the key must be of the string type. Used for Function Assignment
>>> D3 = dict(name='Bob',age=45)>>> D3{'age': 45, 'name': 'Bob'}
Method 4: Dict-key-value sequence# This method is useful if you need to gradually build a sequence of key values, which is often used together with the zip Function
>>> D4 = dict([('name','Bob'),('age',40)])>>> D4{'age': 40, 'name': 'Bob'}

 

Or

 

>>> D = dict(zip(('name','bob'),('age',40)))>>> D{'bob': 40, 'name': 'age'}
Method 5: Dict -- fromkeys Method# If the key values are the same, it is better to use this method and you can use fromkeys for initialization.

 

>>> D5 = dict.fromkeys(['A','B'],0)>>> D5{'A': 0, 'B': 0}
If the key value is not provided, the default value is None.

 

>>> D3 = dict.fromkeys(['A','B'])>>> D3{'A': None, 'B': None}
Dictionary-type-value Traversal method]
>>> D = {'X': 1, 'y': 2, 'z': 3 }# method 1 >>> for key in D: print key, '=>', D [key] y => 2x => 1z => 3 >>> for key, value in D. items (): # method 2 print key, '=>', valuey => 2x => 1z => 3 >>> for key in D. iterkeys (): # method 3 print key, '=>', D [key] y => 2x => 1z => 3 >>> for value in D. values (): # Method 4 print value213 >>> for key, value in D. iteritems (): # Method 5 print key, '=>', valuey => 2x => 1z => 3
Note: using D. iteritems (), D. iterkeys () is much faster than without iter.
One of the common usage of the dictionary replaces switch]

 

In C/C ++/Java, there is a convenient function switch, for example:

 

public class test {public static void main(String[] args) {String s = "C";switch (s){case "A": System.out.println("A");break;case "B":System.out.println("B");break;case "C":System.out.println("C");break;default:System.out.println("D");}}}
To implement the same function in Python,

 

Method 1 is implemented using the if and else statements, for example:

 

from __future__ import divisiondef add(x, y):    return x + ydef sub(x, y):    return x - ydef mul(x, y):    return x * ydef div(x, y):    return x / ydef operator(x, y, sep='+'):    if   sep == '+': print add(x, y)    elif sep == '-': print sub(x, y)    elif sep == '*': print mul(x, y)    elif sep == '/': print div(x, y)    else: print 'Something Wrong'print __name__ if __name__ == '__main__':    x = int(raw_input("Enter the 1st number: "))    y = int(raw_input("Enter the 2nd number: "))    s = raw_input("Enter operation here(+ - * /): ")    operator(x, y, s)
Method 2: Use a dictionary to skillfully implement the same switch function, for example:

 

 

#coding=gbkfrom __future__ import divisionx = int(raw_input("Enter the 1st number: "))y = int(raw_input("Enter the 2nd number: "))def operator(o):    dict_oper = {        '+': lambda x, y: x + y,        '-': lambda x, y: x - y,        '*': lambda x, y: x * y,        '/': lambda x, y: x / y}    return dict_oper.get(o)(x, y) if __name__ == '__main__':      o = raw_input("Enter operation here(+ - * /): ")    print operator(o)





 

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.