Dictionary dict in python

Definition of Dictionary

With key-value storage, it has very fast lookup speed.
Dictionary keys are generally unique, and values can be of any data type.
A dictionary is an unordered collection of data.
Usually the order of output is different from that of definition.

Example:

users = ['user1','user2']
passwds = ['123','456']
print(zip(users,passwds))
print(list(zip(users,passwds)))		list
print(dict(zip(users,passwds)))		Dictionaries

for i in zip(users,passwds):
    print(i)


== value values in dictionaries can be of any data type==

s = {
    'westos':[100,99,88],
    'redhat':[50,60,70]
}
print(s,type(s))


Factory function

d = dict()			Dictionaries
print(d)
print(type(d))

d = dict(a=1,b=2)	Dictionaries
print(d)
print(type(d))
print(d['a']) 		Printing a Of value value


Nesting of Dictionaries

students = {
    '03113009':{
        'name':'wsp',
        'age':18,
        'score':90
    },
    '12345678':{
        'name':'laoli',
        'age':36,
        'score':80
    }
}
print(students['12345678']['name'])			Printing[12345678]Name of student number


Setting the value of all key s is the same

print({}.fromkeys({'1','2'},'000000'))		key1,2 Of value The values are all 000000

The Characteristics of Dictionaries

Dictionary does not support index slicing
Duplicate join of dictionary is meaningless because the key value of dictionary is unique.

d = dict(a=1,b=2)
print(d[0])    #I won't support it


Value value of output key

d = dict(a=1,b=2)
print(d['a'])
print(d['b'])


Member operator

d = dict(a=1,b=2)
print('a' in d)
print('a' not in d)


for loop (default traversal key value)

d = dict(a=1,b=2)
for k in d:
    print(k,d[k])	k and k Corresponding value value

III. Increase in Dictionaries

Add an element: a key value can only correspond to a value
If the key value exists, the value value value corresponding to the original value update is overwritten.
If the key value does not exist, add the key-value pair

services = {
    'http':80,
    'ftp':21,
    'mysql':3306
}

 services['ssh'] = 22		increase key-value value
 print(services)
 services['http'] = 443		key Existing, updated value value
 print(services)


update adds multiple key-value values

services = {
        'http':80,
        'ftp':21,
        'mysql':3306
    }
services_backup = {
    'https':443,
    'tomcat':8080,
    'ssh':22
}

services.update(services_backup)
print(services)

services = {
            'http':80,
            'ftp':21,
            'mysql':3306
        }
services.update(flask=9000,http=8000)		key Existing, updated value value
print(services)        


setdefault adds key value
If the key value exists, do not modify it
If the key value does not exist, add the corresponding key-value

services = {
                'http':80,
                'ftp':21,
                'mysql':3306
            }
services.setdefault('http',9090)	http Existing without modification
print(services)

services.setdefault('oracle',44575)
print(services)

IV. Deletion of Dictionaries

Delete a key, and the corresponding value will also be deleted from the dictionary.

services = {
    'http':80,
    'ftp':21,
    'mysql':3306
}

del services['http']		del Delete the specified key
print(services)


pop deletes the key-value of the specified key
If the key exists, delete and return the value corresponding to the deleted key
If the key does not exist, an error is reported

 services = {
        'http':80,
        'ftp':21,
        'mysql':3306
    }
item = services.pop('mysql')
print(item)
print(services)


popitem deletes the last key-value value value

 services = {
            'http':80,
            'ftp':21,
            'mysql':3306
        }
 item = services.popitem()
 print(item)
 print(services)


Empty the dictionary contents

services = {
            'http':80,
            'ftp':21,
            'mysql':3306
        }
services.clear()
print(services)

V. Viewing Dictionaries

View the key value of the dictionary
print(services.keys())
View the value of the dictionary
print(services.values())
View key-value pairs in dictionaries
print(services.items())

View the value of key
print(services['http'])

get gets the value corresponding to the specified key value
If the key value exists, return the corresponding value value value
If the key value does not exist, it returns None by default; if default exists, it returns default; if the return value needs to be specified, it can be passed.

print(services.get('http')) exists
 print(services.get('https')) does not return None by default
 print(services.get('https','key not exist') does not exist, specifying the return value
 print(services.get('firewall',9090)) does not exist, specifying the return value


for loop traversal

for k,v in services.items()
    print(k,'-->',v)

6. Dictionary Practice

1. Randomize 1000 times in 20-100, rank and count the number of occurrences of each number.

import random
num = []								Define an empty set
for i in range(1000):		
    num.append(random.randint(20,100))

num_s = sorted(num)						Sort and add to dictionary
num_dict = {}							 Define an empty dictionary

for n in num_s:			
    if n in num_dict:					ergodic key
        num_dict[n] +=1					Definition value value
    else:
        num_dict[n] = 1
print(num_dict)

2. Generate 100 bank cards, starting at 6102009, ending at 001-100, password is `redhat'.

card_num = []									Make an empty list
for i in range(100):
    card_num.append('6102009%.3d' %(i+1))		Card number plus 1

card_info = {}.fromkeys(card_num,'redhat')		Define the elements in the list as key´╝îCorresponding value The value is redhat

print('Card number\t\t\t Password')
for k,v in card_info.items():					ergodic key-value Value pair
    print(k,'\t',v)

Tags: MySQL ftp ssh Tomcat

Posted on Thu, 12 Sep 2019 02:37:18 -0700 by cesar110