Getting Started with Python [] 6-1 dict | define, access dict, dict update, traversing dict

1. What is the dict

We already know, list and tuple can be used to represent a collection order, for example, the name of his classmates:

[‘Adam’, ‘Lisa’, ‘Bart’]

Or a list of exam results:

[95, 85, 59]

However, to find the corresponding results according to name, represented by two list is not easy.

If you associate the names and scores of similar composition lookup table:

‘Adam’ ==> 95

‘Lisa’ ==> 85

'Bart' ==> 59

Given a name, you can directly found scores.

Python's dict is dedicated to do this thing.
Means "name" with dict - "results" look-up table as follows:

d = {
    'Adam': 95,
    'Lisa': 85,
    'Bart': 59
}

We called the name key, called the results corresponding value, dict is through to find the key value.

Curly braces {} indicate that this is a dict, and then follow the key: value, you can write it. The last key: value comma can be omitted.

Since dict is set, len () function can calculate the size of any set of:

>>> len(d)
3

Note: a key-value a count, therefore, a size of 3 dict.

Task:
newcomer Paul students score is 75 points, write a dict, the students grades Paul also added to the list.

d = {
    'Adam': 95,
    'Lisa': 85,
    'Bart': 59
}

Code:

d = {
    'Adam': 95,
    'Lisa': 85,
    'Bart': 59,
    'Paul': 75
}

2, visit dict

We have been able to create a dict, used to represent the correspondence between the names and achievements:

d = {
    'Adam': 95,
    'Lisa': 85,
    'Bart': 59
}

So, how to find the corresponding results it by name?

It may simply be used in the form of d [key] to find the corresponding value, and this list like, except that, the index must be used to return the corresponding list element, and using dict key:

>>> print d['Adam']
95
>>> print d['Paul']
Traceback (most recent call last):
  File "index.py", line 11, in <module>
    print d['Paul']
KeyError: 'Paul'

Note: Access dict of value by key, as long as the key exists, dict returns the corresponding value. If the key does not exist, will direct error: KeyError.

  • To avoid KeyError happen, there are two options:
  • First, to determine what the key exists, use in operator:
if 'Paul' in d:
    print d['Paul']

If 'Paul' does not exist, if the statement is determined False, naturally not execute print d [ 'Paul'], thus avoiding errors.

  • The second is to use a get method dict itself provides, when Key does not exist, returns None:
>>> print d.get('Bart')
59
>>> print d.get('Paul')
None

Task:
according to the following dict:

d = {
‘Adam’: 95,
‘Lisa’: 85,
‘Bart’: 59 }

Please print out:

Adam: 95
Lisa: 85
Bart: 59

From writing code:

d = {
    'Adam': 95,
    'Lisa': 85,
    'Bart': 59
}
print 'Adam:',d.get('Adam')
print 'Lisa:',d.get('Lisa')
print 'Bart:',d.get('Bart')

Here Insert Picture Description

Reference Code:

d = {
    'Adam': 95,
    'Lisa': 85,
    'Bart': 59
}
for key in ['Adam', 'Lisa', 'Bart']:
    print "%s: %d"%(key, d[key])


3, dict features

  • Find Fast

The first feature is the dict fast search speed , regardless dict has 10 elements or 100,000 elements, the search speed are the same. The list of search speed gradually decreased with the increase of the elements.

But dict fast search speed is not without cost disadvantage dict is occupying large memory , but also waste a lot of contents, list the contrary, small memory footprint, but look slow.

Since dict is Find by key, therefore, in a dict in, key can not be repeated.

  • Storage disorder

The second characteristic is the dict stored key-value pair is not ordered sequence! This list is not the same:

d = {
    'Adam': 95,
    'Lisa': 85,
    'Bart': 59 }

When we try to print this dict:

>>> print d
{'Lisa': 85, 'Adam': 95, 'Bart': 59}

Print order is not necessarily the order in which we create and order different printing machines are likely to differ, suggesting internal dict is disordered, can not be used dict stored ordered set.

  • Immutable elements

dict third characteristic is a key element to be immutable, Python basic types such as strings, integers, floating point numbers are immutable, it can be used as key.
But the list is variable, it can not serve as key.

You can try what kind of error will be reported when a list as a key.

Immutable this restriction only applied to the key, value if the variable does not matter:

{
    '123': [1, 2, 3],  # key 是 str,value是list
    123: '123',  # key 是 int,value 是 str
    ('a', 'b'): True  # key 是 tuple,并且tuple的每个元素都是不可变对象,value是 boolean
}

The most common key or a string, because the most convenient to use.

Task:
Please design a dict, you can find the name of the score based on the known results are as follows:

Adam: 95,

Lisa: 85,

Bart: 59.

From writing code:

# -*- coding: utf-8 -*-
d = {
    95:'Adam',
    85:'Lisa',
    59:'Bart'   
}


4, update dict

dict is variable, that is, we can always add new key-value to the dict. For example, there dict:

d = {
    'Adam': 95,
    'Lisa': 85,
    'Bart': 59
}

Make new students 'Paul' achievements 72 added to the list, with an assignment statement:

>>> d['Paul'] = 72

Look at the contents of dict:

>>> print d
{'Lisa': 85, 'Paul': 72, 'Adam': 95, 'Bart': 59}

If the key already exists, the assignment will replace the original value with a new value:

>>> d['Bart'] = 60
>>> print d
{'Lisa': 85, 'Paul': 72, 'Adam': 95, 'Bart': 60}

Task:
Please update the following 72 dict according to Paul grades:

d = {
95: ‘Adam’,
85: ‘Lisa’,
59: ‘Bart’
}

From writing code:

d = {
    95: 'Adam',
    85: 'Lisa',
    59: 'Bart'
}

d[72]='Paul'
print d


5, traversing dict

Since a dict is set, therefore, traverse the list traversal dict and the like, can be achieved by a for loop.

Direct use for loop can traverse dict the key:

>>> d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }
>>> for key in d:
...     print key
... 
Lisa
Adam
Bart

Since the value can be acquired by the corresponding key, therefore, in the body of the loop, the value of value can be obtained.

Task:
Please use for looping through the following dict, print out the name: score come.

d = {
    'Adam': 95,
    'Lisa': 85,
    'Bart': 59
}

From writing code:

d = {
    'Adam': 95,
    'Lisa': 85,
    'Bart': 59
}
for key in d:
    print key,':',d.get(key)

Here Insert Picture Description

Published 20 original articles · won praise 0 · Views 412

Guess you like

Origin blog.csdn.net/yipyuenkay/article/details/103926403