The tenth lesson of Python introductory basics--dictionary

    1 Introduction

    From the previous chapters, we can know that the data structure of the list is to organize the values ​​into a structure and refer to its value by number. Is this the only way to refer to powerful Python? The answer is no. In this chapter, we will introduce a new reference method - dictionary. The dictionary is the only built-in mapping type in Python. The values ​​in the dictionary have no special order, but are stored in a specific key (key )under. The range of keys is very wide, including: numbers, strings, tuples.

    The creation of the dictionary, on the one hand, is to allow us to easily look up a specific key to obtain the corresponding value. The other is to allow us to quickly get the position of a particular key. It's convenient and powerful.

    2. Creation and use of dictionaries

    2.1 Create a dictionary

  • Create directly
>>> phonebook={'Alice':'1234','Benth':'5678','Cecil':'9999'}
>>> phonebook
{'Alice': '1234', 'Benth': '5678', 'Cecil': '9999'}

    Looking at the above example carefully, like this method of directly creating a dictionary, we need to remember the format corresponding to the keys and values ​​in the dictionary. Here, the key is the name and the value is the phone number. Corresponding keys and values ​​are separated by colons, different key-value pairs are separated by commas, and the whole is enclosed in curly braces, indicating a complete dictionary. After printing the created dictionary in the shell, you will see that the format is neat and tidy.

  • dict function
>>> phonenumbers=[('name','Alice'),('numbers','12345678')]
>>> p=dict(phonenumbers)
>>> p
{'name': 'Alice', 'numbers': '12345678'}    
>>> p=dict(name='Alice',numbers='123456789')
>>> p
{'numbers': '123456789', 'name': 'Alice'}

    Remember the list function we talked about earlier? It's a type, not a concrete function, like the dict function here, and we have to keep that in mind.

    2.2 Basic dictionary operations

    Dictionaries behave like sequences in many ways, so let's look back at the operations we talked about earlier in sequences:

  • len(d): Returns the number of key-value pairs in d.
  • d[k] returns the value associated with key k.
  • d[k]=v associates the value v with the key k.
  • del d[k] deletes the key-value pair with key k.
  • k in d Checks if there is a key-value pair in d for key k, checks membership.   

    Take a look at an introductory example of a dictionary:

people={
    'Alice':{
        'phone': '2341',
        'addr': 'Foo drive 23'
    },

    'Benth':{
        'phone': '9102',
        'addr': 'Bar street 42'
    },

    'Ceil': {
        'phone': '3158',
        'addr': 'Baz avenue 90'
    }
}

labels={
    'phone': 'phone number',
    'addr': 'address'
}

name=raw_input('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])
/usr/local/bin/python2.7 /Users/yangjiayuan/PycharmProjects/day/day03/dirctory.py
Name: Ceil
Phone number (p) or address (a)?a
Ceil's address is Baz avenue 90.

Process finished with exit code 0

    Take a look at the above code to understand it yourself, and pay attention to the following two points in the process of reading:

  1. keys are arbitrary immutable types
  2. When we try to associate a value with a position in an empty list in a list, we get an error. This is obviously not possible because the location simply doesn't exist, in order to be able to operate successfully we have to initialize it with something like this: [None]*number instead of []. But we can associate a value with an empty dictionary without any error . come and see.
>>> p=[]
>>> p[10]='Alice'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> x={}
>>> x[42]='Alice'
>>> x
{42: 'Alice'}

    This example is worth thinking about!

    3. Dictionary method

    Contrast that with lists, which we learned about earlier. Like other built-in types, dictionaries have methods. These methods are very useful, but may not be used as often as the list or string methods, here I will pick some commonly used methods to give some concrete examples. If the methods you use in the future are not in the ones described below, you can refer to your own data or inquire again to get the use of related methods.

  • clear method
    The clear method is used to clear all items in the dictionary. This is an in-place operation, so there is no return value. 
>>> d={}
>>> d['name']='Alice'
>>> d['number']='22'
>>> d
{'name': 'Alice', 'number': '22'}
>>> returne_value=d.clear()
>>> d
{}
>>> print returne_value
None

    Why talk about this method in the first place? Isn't this just clearing an item in a dictionary? What else is there to use, let's continue to see:

>>> x={}
>>> y=x
>>> x['key']='value'
>>> y
{'key': 'value'}
>>> x={}
>>> y
{'key': 'value'}

     Look again:

>>> x={}
>>> y
{'key': 'value'}
>>> x={}
>>> y=x
>>> x['key']='value'
>>> y
{'key': 'value'}
>>> x.clear()
>>> y
{}

    In the two examples above, x and y originally correspond to the same dictionary, and we "clear" it by associating x to an empty dictionary, which has no effect on y at all, and y is still associated to the original dictionary. But after using the clear method, the elements in the original dictionary are cleared, so y becomes empty.

  • copy method

    The copy method returns a new dictionary with the same key-value pairs. come and see.

>>> x={'hostname':'youzi','ipaddress':'192.168.999.999','username':'yangjiayuan'}
>>> x
{'username': 'yangjiayuan', 'hostname': 'youzi', 'ipaddress': '192.168.999.999'}
>>> y=x.copy()
>>> y
{'username': 'yangjiayuan', 'hostname': 'youzi', 'ipaddress': '192.168.999.999'}
>>> y['username']='wangchao'
>>> y
{'username': 'wangchao', 'hostname': 'youzi', 'ipaddress': '192.168.999.999'}
>>> x
{'username': 'yangjiayuan', 'hostname': 'youzi', 'ipaddress': '192.168.999.999'}

    As you can see, when replacing a value in the copy, the original dictionary is unaffected, but if a value is modified (in-place, not replaced), the original dictionary also changes, because the same value is also stored in the original dictionary .

    The measure to avoid the problem described above is to use a deep copy, copying all the values ​​contained. This can be done using the deepcopy function of the copy module. come and see:

>>> from copy import deepcopy
>>> d={}
>>> d['names']=['Alice','Benth']
>>> c=d.copy()
>>> dc=deepcopy(d)
>>> d['names'].append('Clive')
>>> c
{'names': ['Alice', 'Benth', 'Clive']}
>>> dc
{'names': ['Alice', 'Benth']}
  • get method

    The get method is a more permissive way to access a dictionary, and in general, an error occurs when trying to access an item that does not exist in the dictionary.    

>>> d={}
>>> print d['name']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'name'
>>> print d.get('name')
None
>>> d['name']='Alice'
>>> print d.get('name')
Alice

    The other methods are only used when they are used. In general, they are rarely used. It is enough to master the above three. The upgraded version of the above entry code is given below, and the get method is used to Access the "Database" entity.

people={
    'Alice':{
        'phone': '2341',
        'addr': 'Foo drive 23'
    },

    'Benth':{
        'phone': '9102',
        'addr': 'Bar street 42'
    },

    'Ceil': {
        'phone': '3158',
        'addr': 'Baz avenue 90'
    }
}

labels={
    'phone': 'phone number',
    'addr': 'address'
}

name=raw_input('Name: ')
request=raw_input('Phone number (p) or address (a)?')

key=request

if request=='p':
    key='phone'
if request=='a':
    key='addr'


person=people.get(name,{})
label=labels.get(key,key)
result=person.get(key,'not available')

print "%s's %s is %s. " %(name, label, result )

    Compare the above code and see for yourself, mainly the second half of the code, and understand it well.

    So much is said about the dictionary part, it is a very important concept, and I hope it will attract everyone's attention and attention. Next chapter previews -- conditions, loops, and other statements.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325776267&siteId=291194637