Dictionary / collection

dictionary:

1. read by the key instead of index

  Sometimes called associative array or hash table;

2. any unordered collection of objects

3. The dictionary is variable, and may be arbitrarily nested

4. The key must be unique. If the key appears twice, the latter will be remembered

The dictionary keys must be immutable. It can be numbers, strings, tuples, but not the list.

 

create:

  dic = { 'key1' 'value1', 'key2' 'value2', 'key3' 'value3'}

  dic=dict()

 

zip () function, combination of elements corresponding to a plurality of lists or tuples position tuple, and return the content object containing the zip may be.

a=[1,2,3]

b=[a,b,c]

dic=dict(zip(a,b))

 

dic = dict.fromkeys (a) # create a dictionary is empty

 

del dic or dic.remove () # delete the dictionary.

 

1. By accessing the dictionary keys

  dic.get (key [, default]) # default, when the key does not exist, a default value is returned.

  

print (say [ 'PU']

print ( "Output:", dic.get ( 'PU', 'no such person dictionary')

 

2. traversal

item () returns the key - a list of values

keys () key

values ​​() value

 

 

for item in dic.item():

  print(item)

 

for key,value in dic.item():

  print (key, "contact number is", value)

 

 

3.

import  random

randomdict={i:random.randint(10,100) for i in range(1,5)}

print(randomdict)

 

dic={i:j+'座’  for i,j in zip(name,sign)}

 

 

Set: set variable set and unchangeable set frozenset two kinds. Best application is to remove repeated elements, intersection, union, difference set operation.

1. {,} create a collection

2.set () function can be a list of tuples, and other objects can be converted into an iterative set of

 

Add add ()

Del Delete to delete the entire / pop () remove () removes an element / clear () empty the collection

 

Intersection / union operation / Set difference

&  |  -

print ( "intersecting operation:", a & b)

 

Guess you like

Origin www.cnblogs.com/lelin/p/11568716.html