A dictionary of the Python Way (iii)

Source: Internet
Author: User

This structure is mapped in many languages, and the dictionary is the only built-in mapping type in Python.

Let's look at a dictionary example:

Phonebook = {' Alice ': ' 2341 ', ' Beth ': ' 9102 ', ' Cecil ': ' 3258 '}

The name is the key, the number is the value, the two are separated by a colon, the key in the dictionary is unique, and the value is not unique. An empty dictionary consists of two curly braces: {}. Here are a few more common dictionary operations:

  • Len (d) Returns the number of key-value pairs in D
  • D[K] Returns the value corresponding to the key K
  • D[k] = V associates the value V to the key K
  • Del D[k] Delete item with key K
  • K in D check if D contains keys for key k
The contents of the dictionary can also be added as follows:

Here's a fun example:




Let's look at a cool example of a dictionary and string formatting combined:

This makes it clear and easy for us to modify the HTML text.

Let's explore some dictionary methods below:
1. Clear: Clears all entries in the dictionary, no return value

The usefulness of this method can be reflected by the following example:
As can be seen from the above example, when executing y=x, Y is bound to X, so as x changes, y also changes, but when x={},y is not emptied, Y is also associated with the original dictionary. When you want to empty both x and Y, you can use clear only.

2. Copy: Shallow copy, return a new dictionary with the same key-value pairs, for arrays and object type values, copy can only be shallow copy, that is, copy reference

Y changes to the machine array are reflected in x because they are using the same set of numbers.

A dictionary of the Python Way (iii)

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.