(Basic Python tutorial) learning notes | Chapter 2 | dictionary

Source: Internet
Author: User

(Basic Python tutorial) learning notes | Chapter 2 | dictionary

Chapter 2: dictionary when indexing is poor

The unique built-in ing type in Python is unordered, but all are stored in a specific key. The key can be used as a character, number, or ancestor.

------

Dictionary usage:

Represents the status of the game board. Each key is the number of modifications made to the yuanzu storage file consisting of coordinate values. The file name is used as the key, digital phone number, and address book function to pass the def func (x, * args, ** args ):

If you want to create a list of employees and landline numbers for the company, you can only find Alice's landline.

>>> Names = ['Alice ', 'bob', 'Tom']
>>> Numbers = ['20180101', '20180101', '20180101']
>>> Numbers [names. index ('Alice ')]
'123'

What is really practical is that phonebook ['Alice '] = '000000'. The dictionary is used here.

------

Create and use dictionaries

>>> Phonebooks = {'Alice ': '000000', 'bob': '000000', 'Tom': '000000 '}

Alice is the key, and '123' is a key/value pair. items are separated by commas (,), and key values are separated by commas (,). values can be repeated {} empty dictionaries.

Dict functions:

You can create a dictionary by using another key/value or another dictionary, for example, >>> items = [('name', 'gumby '), ('age', 42)] >>> d1 = dict (items) >>> d1 {'age': 42, 'name ': 'gumby' }>>> d1 ['name'] 'gumby' can also be used to create a dictionary Using Keyword parameters. This is the most useful function of the dictionary, useful in functions: >>> d = dict (name = 'sherry', age = 35) >>> d {'age': 35, 'name ': 'sherry '}
------

Basic dictionary operations:

>>> Len (d) # calculate the number of items in the dictionary, that is, the value of the key/value pair.
2
>>> D ['name'] # returns the value associated with the key.
'Sherry'
>>> D ['name'] = 'Jerry '# associate the value with the key. d [k] = v
>>> D
{'Age': 35, 'name': 'Jerry '}
>>> Del d ['name'] # Delete the key del d [k]
>>> D
{'Age': 35}
>>> 'Age' in d
True


Important differences between dictionaries and lists:

The key data type in the dictionary. You can assign values to integer, no-point, complex, or dictionary types. You can assign values to an empty dictionary, that is, beyond the value outside the index, this is the k in d that is not available in the list: the Key v in l is used to search for the value (the efficiency of searching the dictionary is more efficient than that of the list, the more data, the more obvious the effect)

First: keys in the dictionary can be of any unchangeable type. This is the most powerful function of the dictionary and has a wide range of applicability:
Second: it is also very important. For example, a dictionary can be created in an empty dictionary, and a list won't work:

>>> X = [] >>> x [42] = 'Jerry '# Place 'Jerry' at location 42 Traceback (most recent call last): File"
 
  
", Line 1, in
  
   
X [42] = 'Jerry 'IndexError: list assignment index out of range >>> x ={}>> x [42] = 'Jerry '>>>> x {42: 'Jerry '} if you really want to associate the 'Jerry' value on the 42 th, you must use None for initialization. For example: >>> x = [None] * 43 >>> x [42] = 'Jerry '>>>> x [None, none, none, 'Jerry ']
  
 
# Script program in the phone book
#!/usr/bin/env python#Filename:phonebook.pypeople={'Alice':{'phone':'7890','addr':'street 7890'},'Jerry':{'phone':'1234','addr':'street 1234'},'Wendy':{'phone':'5678','addr':'street 5678'}}labels={'phone':'phone number','addr':'address'}name    = raw_input('Enter name:')request = raw_input('phone number(p) or address(a)?')if request == 'p':  key='phone'if request == 'a':  key='addr'if name in people: print "%s's %s is %s" \          % (name,labels[key],people[name][key])
Dictionary formatted string: (key). If the key exists in the dictionary, it can be printed. This function is very useful in the template system.
>>> Phonebook = {'Alice ': '000000', 'Jerry': '000000', 'wendy ': '200' }>> print "Wendy's phone number is % (Wendy) s "% phonebookWendy's phone number is 8215. Take HTML as an example >>> template = '''...% (Title) s...... % (Title) s...

% (Text) s

......... ''' >>>> Data = {'title': 'My Home page', 'text': 'Welcome to My home Page! '}>>> Print template % dataMy Home PageMy Home Page

Welcome to my home page!

Note: The String. Template class is also very useful in this situation!

------

Dictionary Method:
Clear

>>> d={}>>> d['name']='Alice'>>> d['age'] = 30>>> d{'age': 30, 'name': 'Alice'}>>> return_value = d.clear()>>> d{}>>> return_valueNone
Note the following two situations:
Scenario 1:

>>> x = {}>>> y = x>>> x['key'] = 'value'>>> y{'key': 'value'}>>> x{'key': 'value'}>>> x = {}>>> x{}>>> y{'key': 'value'}
Scenario 2:
>>> x = {}>>> y = x>>> x['key'] = 'value'>>> x{'key': 'value'}>>> x;y{'key': 'value'}{'key': 'value'}>>> x.clear()>>> x;y{}{}
To clear the original dictionary data, you must use the clear () method.

------

Copy:

Light copy: copy data with the same return key/value, but not a copy

>>> x = {'user':'admin','machines':['host1','host2','host3']}>>> y = x.copy()>>> y{'user': 'admin', 'machines': ['host1', 'host2', 'host3']}>>> y['user']='root'>>> del y['machines'][2]>>> y{'user': 'root', 'machines': ['host1', 'host2']}>>> x{'user': 'admin', 'machines': ['host1', 'host2']}
It can be seen that if y is modified, the original x remains unchanged, but if the element is deleted, x will also change. If you want to change the above situation, deep copy is required.
Deep copy: The key/value is the same, and it is a copy
>>> d = {}>>> d['name']=['Sherry','Jerry']>>> c = d.copy()>>> dc= deepcopy(d)>>> d['name'].append('Alice')>>> c{'name': ['Sherry', 'Jerry', 'Alice']}>>> dc{'name': ['Sherry', 'Jerry']}
Fromkeys:

Use the given key to create a new dictionary

# Method 1: >> {}. fromkeys (['name', 'age']) {'age': None, 'name': None} # Method 2: Use the fromkeys function of the dict module >>> dict. fromkeys (['name', 'age']) {'age': None, 'name': None} # If you do not want to use the default None, you can customize it, for example, unknown> dict. fromkeys (['name', 'age'], 'unknown ') {'age': 'unknown', 'name': 'unknown '}
Get: Loose access dictionary
# An error occurs when you access the dictionary by using a common method >>>> d ={}>> print d ['name'] Traceback (most recent call last): File"
 
  
", Line 1, in? KeyError: 'name' # If get is used, the return value is null, which is useful in the program> print d. get ('name') None # You can also customize the returned results, such as N/. if no query is found, the system will return >>> print d. get ('name', 'n'/A') N/A # if there is A value, you can query >>> d = {'name ': 'Jerry '} >>> d. get ('name') 'Jerry'
 
# Scripts using get Functions
[Root @ host] # cat phone. py #! /Usr/bin/env python # Filename: phone. pypeople = {'Alice ': {'phone': '000000', 'addr ': 'street 000000'}, 'Jerry': {'phone ': '123 ', 'addr ': 'street 8125'}, 'wendy ': {'phone': '123', 'addr ': 'street 6501 '}}# use labels = {'phone': 'phone number', 'add': 'address'} name = raw_input ('enter name: ') request = raw_input ('phone number (p) or address (a):') key = requestif request = 'P ': key = 'phone' if request = 'A': key = 'add' person = people. get (name, {}) label = labels. get (key, key) result = person. get (key, 'not available') print "% s is % s" % (name, label, result)
Output result:

[root@host]# ./phone.pyEnter name:AlicePhone number(p) or address(a):pAlice's phone number is 3102[root@host]# ./phone.pyEnter name:JerryPhone number(p) or address(a):papaJerry's papa is Not Available
It can be seen that in the get method in the program, even if there is no prepared value, it can make a proper response.

------

Has_keySimilar to k in d, check whether the dictionary has a given key.

>>> d={}>>> d.has_key('name')False>>> d['name']='John'>>> d.has_key('name')True
Note: This function is not included in Python 3.0.

------

ItemsAndIteritems

>>> D = {'title': 'python web page', 'url': 'http: // www.python.org ', 'spam': 0 }>>> d. items () # returns an unordered list [('url', 'HTTP: // www.python.org '), ('spam', 0), ('title ', 'python webpage')]> d. iteritems () # An Iteration object is returned.
 
  
>>> L = d. iteritems () # use the list function to convert an iteration object to a list> list (l) [('url', 'HTTP: // www.python.org '), ('spam ', 0), ('title', 'python webpage')]
 
Note: iteritems functions are more efficient.

------

Pop: Used to obtain and delete the value of a given key.

>>> D = {'X': 1, 'y': 2, 'z': 3 }>>> d. pop () # note that the value cannot be blank. This list must be distinguished by Traceback (most recent call last): File"
 
  
", Line 1, in? TypeError: pop expected at least 1 arguments, got 0 >>> d. pop ('x') 1 >>>> d {'y': 2, 'z': 3}
 
------

Popitem(): The last item is displayed. This is similar to the pop () method in the list, but the dictionary is unordered.

This method is useful if you want to remove and process items one by one, because you do not need to obtain the key value.

>>> d = {'title':'Python web page','url':'http://www.python.org','spam':0}>>> d.popitem()('url', 'http://www.python.org')>>> d{'spam': 0, 'title': 'Python web page'}
------

Setdefault: Similar to get

>>> D ={}# if the value is null, setdefault is valid >>> d. setdefault ('name', 'n'/A') 'n'/A'> d {'name ': 'N'/A' }>>> d = {'name': 'Jerry '} # if there is A value, setdefault does not take effect >>> d. setdefault ('name', 'n'/A') 'Jerry '> d {'name': 'Jerry '}
------

ValuesAndItervalues

Values: return the value itervalues in the dictionary as a list: return the iteration object >>>> d ={}>> d [1] = 1 >>>> d [2] = 2 >>> d [3] = 3 >>> d [4] = 4> d. values () [1, 2, 3, 4] >>> d. itervalues ()
 
  
>>> L = d. itervalues () >>> list (l) [1, 2, 3, 4]
 
------

Update: You can use one dictionary to update another.

>>> d = {... 'title':'Python Web Page',... 'url':'http://www.python.org',... 'changed':'Mar 14 22:09:05 GMT 2014'... }>>> x = {'title':'Python Language Page'}>>> d.update(x)>>> d{'url': 'http://www.python.org', 'changed': 'Mar 14 22:09:05 GMT 2014', 'title': 'Python Language Page'}
------

Functions in this chapter:

Dict (seq) uses (key/value) pairs (or ing and keyword parameters) to create a dictionary.

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.