Python Basics: Zip and dict detailed

Source: Internet
Author: User

A. zip function: Accepts any number of sequences (including 0 and 1) as parameters, returning a tuple list.

1. Example 1:

x = [1, 2, 3]y = [4, 5, 6]z = [7, 8, 9]xyz = Zip (x, y, z) print xyz

The result of the operation is:

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

From this result, we can see the basic operation of the ZIP function.

2. Example 2:

x = [1, 2, 3]y = [4, 5, 6, 7]xy = Zip (x, y) print xy

The result of the operation is:

[(1, 4), (2, 5), (3, 6)]

From this result, we can see how the length of the zip function is handled.

3. Example 3:

x = [1, 2, 3]x = Zip (x) print X

The result of the operation is:

[(1,), (2,), (3,)]

From this result you can see how the ZIP function works when there is only one parameter.

4. Example 4:

x = Zip () print X

The result of the operation is:

[]

From this result, you can see how the zip function works without parameters.

5. Example 5:

x = [1, 2, 3]y = [4, 5, 6]z = [7, 8, 9]xyz = Zip (x, y, z) u = Zip (*xyz) print U

The result of the operation is:

[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

It is generally thought that this is a unzip process, and its operating mechanism is this:

Before running Zip (*xyz), the value of XYZ is: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

Then, Zip (*xyz) is equivalent to zip ((1, 4, 7), (2, 5, 8), (3, 6, 9))

So the result is: [(1, 2, 3), (4, 5, 6), (7, 8, 9)]

Note: Using *list/tuple in a function call means separating the list/tuple, passing it as a positional parameter to the corresponding function (provided that the corresponding function supports an indefinite number of positional parameters)

6. Example 6:

x = [1, 2, 3]r = Zip (* [x] * 3) Print R

The result of the operation is:

[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

It operates in such a way that:

[x] generates a list of lists that have only one element x

[x] * 3 generates a list of lists, it has 3 elements, [x, X, X]

The meaning of Zip (* [x] * 3) is clear, zip (x, x, x)

Second, dict operation

1. Create a dictionary using zip

Key = ' ABCDE '

Value = Range (1, 6)

Dict (Zip (key, value))

2. Use items () to traverse the dictionary

For Key,value in D.items ():

3. use GET, pop to get/delete key

First, Dict[key] and delete Dict[key] can also get/delete key. However, a keyerror exception is thrown when key does not exist. To avoid throwing exceptions, you can use the Get and pop functions with the Defaut parameter

    • Get (key[, default])
      If key is in the dictionary, the corresponding value is returned, otherwise the default is returned. So it never throws an exception.
    • Pop (key[, default])
      If default is not set, deleting key will throw an exception if key is not in the dictionary. Add default when used.

4, Dict (Dict1, **dict2) Merge two dictionaries

Merging two dictionaries you can divide two dictionaries into key-value pairs, connect two key-value pairs, and create a new dictionary. That is dict(dict1.items()+dict2.items()) , but the efficiency is somewhat low.
Use a more efficient dict(dict1, **dict2) connection to two dictionaries.

in []: dict1out[29]: {' A ':1,' B ':2,' C ':3}in [(): dict2out[30]: { ' d ': 4,  ' E ': 5,  ' F ': 6} In [31]: dict (dict1, **dict2) Out[31]: { ' a ': 1,  ' B ': Span class= "DV" >2,  ' C ': 3,  ' d ': 4,  ' E ': 5,  ' F ': 6}         
-m timeit -s ‘dict1=dict2=dict(a=1,b=2)‘ ‘dict3=dict(dict1,**dict2)‘1000000 loops, best of 3: 0.573 usec per loop$ python -m timeit -s ‘dict1=dict2=dict(a=1,b=2)‘ ‘dict3=dict(dict1.items()+dict2.items())‘100000 loops, best of 3: 2.21 usec per loop

5. Use keys () and values () to get the keyword and value

D.keys ()

D.values ()

6, update the dictionary using update (), the same as 4 dict (Dict1, **dict2) effect

1Dict1 = {"a":"Apple","b":"Banana"}2 Print(Dict1)3Dict2 = {"C":"Grape","D":"Orange"}4 dict1.update (DICT2)5 Print(Dict1)
View Code

Output:

{' A ': ' Apple ', ' B ': ' Banana '}
{' C ': ' Grape ', ' a ': ' Apple ', ' B ': ' Banana ', ' d ': ' Orange '}

7. Sorting using sorted

#按照key排序
Print (sorted (Dict1.items (), Key=lambda d:d[0]))
#按照value排序
Print (sorted (Dict1.items (), Key=lambda d:d[1]))

8. Use SetDefault to set default values

Dict = {}
Dict.setdefault ("a")

9. Pop () and clear () delete

1d={"a": 1,"b": 2,"C": 3}2 Print(d)3 #Output4 #{"A": 1, "B": 2, "C": 3}5 6D1=d.pop ("a")#d1=17 Print(d)8 #Output9 #{"B": 2, "C": 3}Ten  OneD2=d.pop ("F", 100)#d2=100 A Print(d) - #Output - #{"B": 2, "C": 3}
View Code

D.clear () #将字典d清空

Print (d) #输出 {}

10. Use the Fromkeys () function to create a new dictionary, which is the key for the dictionary of elements in the sequence SEQ, and value is the initial value corresponding to all keys in the dictionary.

1 seq={'name','age','score  '}2 d=dict.fromkeys (seq,100)3print(d) 4 # Output 5 # {' name ': +, ' age ': +, ' score ':
View Code

11. Use Popitems () to randomly return and delete a pair of keys and values (items) in the dictionary

1seq={'name',' Age','score'}2D=dict.fromkeys (seq,100)3 Print(d)#output: {' age ': +, ' name ': +, ' score ':4D2=D.popitem ()5 Print(D2)#output: (' age ', +)6 Print(d)#output: {' name ': +, ' score ':
View Code







Python Basics: Zip and dict detailed

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.