Python -- about dict, Python -- dict

Source: Internet
Author: User

Python -- about dict, Python -- dict

This article is excerpted from MOOC getting started with Python.

 

1. dict features

Dict is represented by braces {}, and then written according to key: value. The last key: value comma can be omitted.

①,Fast dict search,No matter whether dict has 10 or 0.1 million elements, the search speed is the same.. The search speed of list gradually decreases with the increase of elements.

The disadvantage of dict is that it occupies a large amount of memory and wastes a lot of content., The list is the opposite. The memory usage is small, but the search speed is slow.

② Dict uses the key to find the value, so the key cannot be repeated, while the value can be repeated.

③ The "key: value" stored by dict is unordered, that is, the index number cannot be sliced.

The basic types of Python, such as strings, integers, and floating-point numbers, are immutable and can all be used as keys. But the list is variable and cannot be used as the key.

UseDictIndicates"Name"-"score"The search table is as follows:

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

We setThe name is key., CorrespondingThe score is called value.Dict is throughKeyTo findValue.

2. Access dict

Create a dict to indicate the correspondence between the name and score:

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

Use d [key] to find the corresponding value, which is similar to list. The difference is that,The list must use the index to return the corresponding element, while the dict uses the key:

 23:30:12

Note:Access the value of dict through the key. If the key exists, dict returns the corresponding value. If the key does not exist, an error is reported: KeyError.

There are two methods to avoid KeyError:

First, determine whether the key exists. Use the in OPERATOR:

 if 'Paul' in d:
 print d['Paul']

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

The second is to use a get method provided by dict itself. If the Key does not exist, None is returned:

 >>> print d.get('Bart')
 59
 >>> print d.get('Paul')
 None
3. Update dict
 
Dict is variable. You can add new key-value to dict at any time. For example, dict already exists:
 d = {
 'Adam': 95,
 'Lisa': 85,
 'Bart': 59
 }

Add 'Paul ''s score 72 to the assignment statement:
 >>> d['Paul'] = 72 

Let's take a look at dict content:
 >>> print d
 {'Lisa': 85, 'Paul': 72, 'Adam': 95, 'Bart': 59}

If the key already exists, the assignment replaces the original value with the new value:
 >>> d['Bart'] = 60
 >>> print d
 {'Lisa': 85, 'Paul': 72, 'Adam': 95, 'Bart': 60}
4. Traverse/iterate dict
I. for Loop traversal: Because dict is also a set, traversing dict is similar to traversing list, and can be implemented through for loop.
 >>> d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }
>>> for key in d:
 print key,'-',d[key]
 Lisa - 85
Adam - 95
Bart - 59
Ii. values ()/itervalues () method: return the value of dict
Values () method: converts a dict to a list containing values.
 >>> d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }
>>> print d.values()
[85, 95, 59]
>>> for v in d.values():
 print v
 85
95
59
UseItervalues ()Method substitutionValues ()Method, and the iteration effect is exactly the same. WhileItervalues ()The method is not converted, and values are retrieved from dict in sequence during iteration. Therefore, the itervalues () method saves the memory required to generate the list than the values () method.
Iii. items ()/iteritems () method: return the key and value of dict.
 
Dict objectItems ()Value returned by the method:
 >>> d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 } >>> print d.items() [('Lisa', 85), ('Adam', 95), ('Bart', 59)]

As you can see, the items () method converts a dict object to a list containing tuple. This list is iterated to obtain both the key and value:
 >>> for key, value in d.items(): ... print key, ':', value ... Lisa : 85 Adam : 95 Bart : 59

There is an itervalues () similar to values,Items ()There is also a correspondingIteritems ()Iteritems () does not convert dict to list, but constantly provides tuple during iteration. Therefore, iteritems () does not occupy additional memory.

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.