A collection of practical techniques for creating, traversing, and adding dictionaries in python

Source: Internet
Author: User
Tags mul
The field is Python is the only key-value type in the dictionary, and is a very important data structure in Python, because it stores data in a hashed manner, with an O (1) complexity, which is very fast. The common uses of dictionaries are listed below.
List of common methods in a dictionary

The code is as follows:


#方法 #描述
-------------------------------------------------------------------------------------------------
D.clear () #移除D中的所有项
D.copy () #返回D的副本
D.fromkeys (Seq[,val]) #返回从seq中获得的键和被设置为val的值的字典. Can do class method calls
D.get (Key[,default]) #如果D [key] exists, returns it, otherwise returns the given default value of None
D.has_key (Key) #检查D是否有给定键key
D.items () #返回表示D项的 (key, value) pair list
D.iteritems () #从D. Items () Returns an iterative object in the (key, value) pair
D.iterkeys () #从D的键中返回一个可迭代对象
D.itervalues () #从D的值中返回一个可迭代对象
D.keys () #返回D键的列表
D.pop (Key[,d]) #移除并且返回对应给定键key或给定的默认值D的值
D.popitem () #从D中移除任意一项 and returns it as a (key, value) pair
D.setdefault (Key[,default]) #如果D [key] exists and returns it, otherwise the default value of None is returned.
D.update (Other) #将other中的每一项加入到D中.
D.values () #返回D中值的列表

Ii. Five ways to create a dictionary

Method One: General method

The code is as follows:


# This method is convenient if you can spell the whole dictionary in advance
>>> D1 = {' name ': ' Bob ', ' Age ': 40}


Method Two: Dynamic creation

The code is as follows:


# This method is convenient if you need to create a field of the dictionary dynamically
>>> D2 = {}
>>> d2[' name '] = ' Bob '
>>> d2[' age '] = 40
>>> D2
{' Age ': +, ' name ': ' Bob '}


Method Three: dict--keyword form

The code is as follows:


# code is less, but the key must be a string type. Often used for function assignment
>>> D3 = dict (name= ' Bob ', age=45)
>>> D3
{' Age ': $, ' name ': ' Bob '}

Method Four: dict--key value Sequence

The code is as follows:


# This is useful if you need to build a sequence of key values, often in conjunction with the ZIP function
>>> D4 = dict ([' Name ', ' Bob '), (' Age ', 40)])
>>> D4
{' Age ': +, ' name ': ' Bob '}


Or

The code is as follows:


>>> D = dict ((' Name ', ' Bob '), (' Age ', 40))
>>> D
{' Bob ': +, ' name ': ' Age '}


Method Five: Dict--fromkeys method # If the values of the keys are the same, it is better in this way and can be initialized with Fromkeys.

The code is as follows:


>>> D5 = Dict.fromkeys ([' A ', ' B '],0)
>>> D5
{' A ': 0, ' B ': 0}


If the value of the key is not provided, the default is None

The code is as follows:


>>> D3 = Dict.fromkeys ([' A ', ' B '])
>>> D3
{' A ': None, ' B ': none}

The method of key value traversal in dictionary

The code is as follows:


>>> D = {' x ': 1, ' Y ': 2, ' Z ': 3} # Method One
>>> for key in D:
Print key, ' = = ', D[key]
y = 2
x = 1
z = 3
>>> for key, value in D.items (): # Method Two
Print key, ' = = ', value
y = 2
x = 1
z = 3

>>> for key in D.iterkeys (): # Method Three
Print key, ' = = ', D[key]
y = 2
x = 1
z = 3
>>> for value in D.values (): # method Four
Print value
2
1
3
>>> for key, value in D.iteritems (): # method Five
Print key, ' = = ', value

y = 2
x = 1
z = 3

Note: Using D.iteritems (), the D.iterkeys () method is much faster than no ITER.

Iv. One of the common uses of dictionaries instead of switch

In the C/c++/java language, there is a convenient function switch, for example:

The code is as follows:


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 functionality in Python,
Method one is implemented with the IF, else statement, for example:

The code is as follows:


From __future__ Import Division

def add (x, y):
return x + y

def sub (x, y):
return x-y

def mul (x, y):
return x * y

def div (x, y):
return x/Y

def 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 two, using a dictionary to skillfully implement the same switch function, such as:

The code is as follows:


#coding =GBK

From __future__ Import Division

x = 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)

  • 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.