Dictionary and set in Python, Python dictionary set

Source: Internet
Author: User

Dictionary and set in Python, Python dictionary set

I. Dictionary (dict)

1. Overview

The dictionary is the only ing type in Python.

You can only use immutable objects (such as strings) as Dictionary keys, but you can use immutable or variable objects as Dictionary values.

Key-value pairs are marked in the dictionary in this way: d = key1: value1, key2: value2. Note that their key/value pairs are separated by colons, and each pair is separated by commas,

All of these are included in curly brackets.

The key/value pairs in the dictionary are unordered.

A dictionary is an instance/Object of the dict class.

2. Create and access

You can directly create a key/Value Pair using curly braces. You can create an empty dictionary in this way. The dictionary can be indexed, but the index value is a key value.

Use the built-in function dict () to create a dictionary. Note that the entire function has only one parameter, as shown below:

Dict3 = dict ('F', 70), ('I', 105), ('h', 115), ('C', 67 ))), you only need to let it find the ing relationship.

You can also specify the keyword parameter to create a dictionary:

Dict4 = dict (Turing = 'let programming change the world'). Note that the key is that Turing cannot be enclosed by quotation marks and an error is returned.

You can also use a key to modify the value of a dictionary. If this key exists, the value is changed. If this key does not exist at all, another key/value pair is added. For example:

Dict4 ['turing'] = 'Programming together'

Dict4 ['edison '] = 'fa Ming Jia'

>>> Dict4

{'Turing': 'Everyone programming together ', 'edison': 'fa Ming Jia '}.

3. built-in dictionary Methods

1) fromkeys ()

>>> Dict1 = {}

>>> Dict1.fromkeys (1, 2, 3 ))

{1: None, 2: None, 3: None}
>>> Dict1.fromkeys (1, 2, 3), 'number ')
{1: 'number', 2: 'number', 3: 'number '}
>>> Dict1.fromkeys (1, 2, 3), ('one', 'two', 'three '))
{1: ('one', 'two', 'three '), 2: ('one', 'two', 'three'), 3: ('one ', 'two', 'three ')}

>>> Dict1.fromkeys (1, 3), 'number ')

{1: 'number', 3: 'number '}

The fromkeys method is used to create a dictionary with two parameters: a key and a value. Note that the second parameter will be assigned to all the keys, and there is no smart one-to-one matching.

There is no way to modify the key value in this way. If the key value is forcibly modified, a new dictionary will be created.

2) keys () values () items ()

Traverse keys, values, and items respectively.

3) get ()

When the index is not a dictionary key, an error occurs when accessing the output. You can use the get () method to cleverly solve this problem.

>>> Print (dict2 [31])

Like
>>> Print (dict2 [32])
Traceback (most recent call last ):
File "<pyshell #17>", line 1, in <module>
Print (dict2 [32])
KeyError: 32
>>> Dict2.get (32)
>>> Print (dict2.get (32 ))
None
>>> Dict2.get (32, 'wooden you ')
'Wood you'
>>> Dict2.get (31, 'wooden you ')
'Za'

4) clear ()

Clear the dictionary. If you directly assign the dictionary you want to clear to an empty dictionary, there are many differences with the clear () method. Sometimes there may be threats, or you should use the clear () method.

>>> Dict2.clear ()

>>> Dict2
{}
>>> Dict2 = {}
>>> A = {' ': 'haha '}
>>> B =
>>> B
{'Hello ': 'haha '}
>>> A = {}
>>> B
{'Hello ': 'haha '}
>>> A = B
>>>
{'Hello ': 'haha '}
>>> B
{'Hello ': 'haha '}
>>> A. clear ()
>>>
{}
>>> B

{}

5) copy ()

The shortest code is different from the value assignment operation:

>>> A = {1: 'one', 2: 'two', 3: 'Three '}
>>> B = a. copy ()
>>> C =
>>> C
{1: 'one', 2: 'two', 3: 'Three '}
>>>
{1: 'one', 2: 'two', 3: 'Three '}
>>> B
{1: 'one', 2: 'two', 3: 'Three '}
>>> Id ()
57877832
>>> Id (B)
57838536
>>> Id (c)
57877832

6) pop () and popitem ()

One is the pop-up value, the other is the pop-up item, and the latter is the random pop-up.

>>> A. pop (2)
'Two'
>>>
{1: 'one', 3: 'Three '}
>>> A. popitem ()
(1, 'one ')

7) setdefault ()

Add a key or a key/value pair. For example:

(Note: The order after adding is random)

>>> A. setdefault ('sq ')
>>>
{'Sq ': None, 3: 'Three '}
>>> A. setdefault (5, 'five ')
>>>
{3: 'Three ', 5: 'five', 'sq': None}

8) update ()

Use a dictionary to update the dictionary. If a key in the parameter dictionary has an original dictionary, it will update its value. If not, it will be automatically added to the new dictionary.

2. set)

1. Overview

A set is the cousin of a dictionary. curly braces are not just the dictionary privilege. A set is created when a bunch of non- ing elements are enclosed in curly brackets.

>>> Num2 = {1, 2, 3, 4}
>>> Type (num2)
<Class 'set'>

2. Like the concept in mathematics, a set has the opposite sex and is unordered (so the set cannot be used for indexing ).

>>> Num = {1, 2, 3, 4, 6, 3, 2}
>>> Num
{1, 2, 3, 4, 6}
>>> Num [2]
Traceback (most recent call last ):
File "<pyshell #4>", line 1, in <module>
Num [2]
TypeError: 'set' object does not support indexing

3. the built-in factory function set () can be used to create a set. parameters can be lists, tuples, or even strings.

>>> Set1 = set ([1, 2, 3, 4, 5])
>>> Set1
{1, 2, 3, 4, 5}

4. Because of the ry of the set, it provides a clever way to remove the same elements in the sequence.

List2 = list (set (list1 ))

The disadvantage is that it cannot guarantee the same sequence as the original sequence and should be used with caution.

5. add () remove () built-in method of the Set ()

The frozenset () function that creates an immutable set ().

6. Summary of built-in methods for other common sets

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.