Python Note 04: Dictionaries

Source: Internet
Author: User
Tags shallow copy

4.1 Dictionary use Dictionary: Data structures that refer to values by name, also known as values in the mapping dictionary, do not have a special order, but are stored in a specific key under the dictionary provided by the function:quickly find specific key-value correspondence

In some cases, dictionaries are better than lists, such as:

1. Identify the desired state of a game, each key is a tuple of coordinate values 2. Store the file modification time, using the file name as the key 3. Digital phone, Address book Problem: Why use strings instead of integers to represent phone numbers? To prevent the generation of false recognition 4.2 create and use a dictionary
Phonebook = {'Alice': 1567,'Beth':'3657 ','Cecil': 0010}
Dictionaries have multiple key-value pairs consisting of two curly braces, such as {} NOTE: The keys in the dictionary are unique, the values are not unique 4.2.1 The DICT function can use the DICT function to build a dictionary through other mappings (such as dictionaries) or sequences (key, value) pairs
 items = [( " name  , "  gumby  ", ( " age   ", 43)]d  = Dict (items)  >>> print   d{ Span style= "COLOR: #800000" > " age  "  :  " name   ' :  '  gumby   ' } 
The basic operation of the 4.2.2 Dictionary len (d): Returns the total number of key-value pairs of D d[k]    : Returns the value associated to the key K D[k]=v: Associating the value V to the key K del D[k]: Delete the key k in D   : Check if D contains items with key K   key type: Not necessarily integral type, can be any immutable type, such as floating-point (real), string or tuple 4.2.3 Dictionary formatted string
Phonebook = {'Alice': 1567,'Beth':'3657 ','Cecil': 0010}"Cecil ' s phone number is% (Cecil ) s. " % phonebook"Cecil ' s phone number is 8. "
4.2.4 Dictionary method 1.clear: Clears all items in the dictionary this operation does not return a value of 2.copy: Returns a new dictionary with the same key-value pair This kind of replication is shallow copy shallow copy:
x = {'username':'Admin',' Machine':['Foo','Bar','Baz']}y=x.copy () y['username'] ='MLH'y[' Machine'].remove ('Bar')PrintyPrintx#The results are as follows{'username':'MLH',' Machine': ['Foo','Baz']}{'username':'Admin',' Machine': ['Foo','Baz']}
As you can see, the original dictionary is not affected when the value is substituted in the copy, but if a word is modified, the original dictionary will also change because the same is stored in the original dictionary.one way to avoid shallow copying is to use deep copy to copy all the values it contains, using the deepcopy of the copy module to implementDeep copy:
 fromCopyImportDeepcopyd={}d['names'] = ['alfed','Bertand']c=d.copy () DC=deepcopy (c) dc['names'].append ('Clive')PrintCPrintDC#The results are as follows:{'names': ['alfed','Bertand']}{'names': ['alfed','Bertand','Clive']}
3.fromkeys: Create a new dictionary with the given key
>>> {}.fromkeys (['name',' Age']){' Age': None,'name': None}>>> Dict.fromkeys (['name',' Age']){' Age': None,'name': None}
4.get: More relaxed access to the dictionary method in general, if you attempt to access an item that does not exist in the dictionary, an error occurs, and a get does not
>>> d = {}>>> d['name']traceback (most recent call last):   " <stdin> "  in <module>'name'print d.get (' name ' ) None
You can see that, but when you access a nonexistent key with GET, there is no exception and you get the None value. You can also customize the default values to replace None
print d.get ('name','N/a') nth/A
If the key exists, get is used as a normal dictionary query.
>>> d['age ') = 43>>> d.get ('age' )43
5.haskey: Determine if there is a specific key equivalent to the expression K in D.6.item and Iteritems: Returns the value of the dictionary as a list the items method returns all items in the dictionary as a list, with each item in the list represented as a (key, value) pair. But the item does not follow a specific order when it returns
>>> d = {'name':'Lily','age' : >>> d.items (' age', +), (' name ' ' Lily ')]
The Iteritems method works roughly the same, but returns an iterator object instead of a list
>>> it = d.iteritems ()print  itprint  list (IT) [('  Age', ' ('name''Lily')]
7.keys and Iterkeys: Returns the keys in the dictionary as a list the keys method returns the key in the dictionary as a list, Iterkeys returns an iterator for the key 8.pop: Gets the value of the corresponding key, and deletes the key value pair
 >>> d{  " age  " :  " name  " :  " lily   " }  >>> D.pop ( '  name  "  )   " lily  "  >>> d{   " age   ' : ' 
9.popitem: The last element that pops up is listed in List.pop, which pops up the last element of the list. But the difference is that popitems pops up random entries because the dictionary does not have "last element" or other concepts about the order. Weakness one by one the removal and processing of items, this method is very effective 10.setdefault: The given key is associated with a value similar to the Get method, can get the value associated with a given key, in addition, SetDefault can also set the corresponding key value in the dictionary without the given key
>>> d = {}>>> D.setdefault ('name','N /A')'N /A'>>>d{'name':'N /A'}>>> d['name'] ='Gumby'>>> D.setdefault ('name','N /A')'Gumby'>>>d{'name':'Gumby'}
As you can see, when the key does not exist, SetDefault returns the default value and the corresponding update dictionary. If the key exists, it returns its corresponding value, but does not change the dictionary. The default value is optional, which, like get, uses none if not set
>>> d = {}>>> D.setdefault ('name', []). Append (My_sister)>>>d{'name': ['Anne']}>>> D.setdefault ('name', []). Append ('My_sister')>>>d{'name': ['Anne','My_sister']}
11.update: Update Another dictionary example with one dictionary entry:
>>> d = {'name':'Gumby',' Age': 42,'Address':'Beijing'}>>> x = {'name':'Lily'}>>>d.update (x)>>>d{' Age': 42,'name':'Lily','Address':'Beijing'}#the name value in D has been updated with X>>>x{'name':'Lily'}
12.values and Itervalues: Returns the value in the dictionary The Values method returns the value in the dictionary as a list, Itervalues returns the worthy iterator 4.3 summary mapping: Mappings can identify elements with any immutable object. The most common types are strings and tuples. Python's only built-in mapping type is a dictionary-formatted string using a dictionary: You can apply string formatting to a dictionary by including a name (key) in the format specifier. When using tuples in string formatting, you also need to set the format specifier for each element in the tuple, which can be used less than the dictionary in the dictionary when using the dictionary:

Python Note 04: Dictionaries

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.