Dictionary of Python introduction

Dictionary of Python introduction

1, What is a dictionary

1. The realization principle of dictionary

The implementation principle of the dictionary is similar to that of the difference dictionary. When we look up a word in the dictionary, one way is to turn back from the first page of the dictionary,

Until we find the word we are looking for. This method is to find the elements in the list. Its disadvantage is that the more words in the dictionary, the more efficient it is to find them

The lower it is. The second method is to find the page number corresponding to the word in the index table of the dictionary (such as the radical table), and then go directly to the page corresponding to the word,

Its advantage is: the efficiency of searching will not decrease with the increase of the number of words in the dictionary. No matter which word is searched, the searching speed is very fast.

2. Features of dictionaries

a) When all elements in the dictionary are a key value, the specified key can always map to a unique value. There can be no duplicate in the dictionary,

But there can be duplicate value s.

b) The elements in the dictionary are unordered. The order is not important, but the mapping between key and value.

c) The key in the dictionary must be immutable. When accessing the key value pair in the dictionary, the system will call the built-in function hash to calculate the value according to the specified key

Storage location, that is, hash value. For the specified key, in order to ensure that the hash value calculated each time is the same, the key must be an immutable object. in other words,

Only immutable objects have hash values.

d) Dictionaries can be dynamically scaled as needed. The system dynamically allocates and reclaims memory as needed, so the capacity of the dictionary does not need to be declared in advance before use.

e) Dictionaries waste a lot of memory. Compared with lists, they trade space for query time.


2, Why a dictionary is needed

For example: a name and phone number are stored in the phone book:

Zhang San 111111111

Li Si 222222

Wang Wu 333333333

Zhao Liu 444444444

Name of Fu

names = ['Zhang San', 'Li Si', 'Wang Wu', 'Zhao Liu']

#Phone number

numbers = ['111111111','222222222','333333333','444444444']

print(numbers[names.index('Zhang San')]) # 111111111
for i,n in zip(names,numbers):
    print(i,n)
#Or use zip for parallel traversal
//Zhang San 111111111
//Li Si 222222
//Wang Wu 333333333
//Zhao Liu 444444444


It's better to store all the names and phone numbers in a data structure of phonebook and get the corresponding phone numbers directly.

phonebook = {'Zhang San':'111111111','Li Si':'222222222','Wang Wu':'333333333','Zhao Liu':'444444444'}
print(phonebook['Zhang San']) #111111111


3, Dictionary creation

1. How to use curly braces {}

d1 = {'zhangsan':18,'lisi':19,'wangwu':20}
print(d1) # {'zhangsan': 18, 'lisi': 19, 'wangwu': 20}
#Empty dictionary creation
d1 = {}
print(d1) # {}


2. Use the built-in function dict()

#Pass dictionary parameters
d2 = dict({'zhangsan':18,'lisi':19,'wangwu':20})
print(d2) # {'zhangsan': 18, 'lisi': 19, 'wangwu': 20}
#Passing a list with tuples
d2 = dict([('zhangsan',18),('lisi',19),('wangwu',20)])
print(d2) # {'zhangsan': 18, 'lisi': 19, 'wangwu': 20}
#Pass the zip iteration object
d2 = dict(zip(['zhangsan','lisi','wangwu'],(18,19,20)))
print(d2) # {'zhangsan': 18, 'lisi': 19, 'wangwu': 20}


4, Addition, deletion, modification and search of dictionaries

1. Check operation

#Pass index using method of []
d1 = dict([('name','zhangsan'),('age',18)])
print(d1['name'])
print(d1['age'])

#get method
print(d1.get('name')) # zhangsan
print(d1.get('age'))  # 18
print(d1.get('abc','NONE')) #get allows us to customize the return value, if there is no corresponding value or index


2. Add operation

d1['hobby'] = 'games'  #Add a nonexistent key value pair
d1.update([('wang',17),('li',16)])  #Using the update method, add multiple key value pairs at a time
d1.update({'tianqi':'19'})
d1.update(zhangsan1 = 18)
print(d1)  # {'name': 'zhangsan', 'age': 18, 'hobby': 'games', 'wang': 17, 'li': 16, 'tianqi': '19', 'zhangsan1': 18}


3. Change operation

d1['age'] = '27'
d1.update(wang = 22,tianqi = 23)
d1.update({'name':'zhangsan1'})
d1.update(hobby = 'read')
d1.update([('tianqi',23),('zhangsan',25)])
print(d1)  # {'name': 'zhangsan1', 'age': '27', 'hobby': 'read', 'wang': 22, 'li': 16, 'tianqi': 23, 'zhangsan1': 18, 'zhangsan': 25}


4. Delete operation

d1 = {'name': 'zhangsan1', 'age': '27', 'hobby2': 'games', 'hobby1': 'read', 'zhangsan': 25}
d1.pop('name')  #Delete a specified key
d1.popitem()  #Randomly delete a key
del(d1['age']) #Delete a specified key
print(d1)  # {'hobby2': 'games', 'hobby1': 'read'}
d1.clear() #Clear list
print(d1) # {}


5, View of dictionary

1. Call the keys, values, and items methods to print the dictionary view

print(d1.keys(),type(d1.keys()))  #Dict [keys (['name ','age','hobby2 ','hobby1','zhangsan ']) < class' dict [keys])
print(d1.values(),type(d1.values())) #Dict [values (['zhangsan1 ',' 27 ',' games', 'read', 25]) < class' dict [values' > Print Dictionary values
print(d1.items(),type(d1.items())) # dict_items([('name', 'zhangsan1'), ('age', '27'), ('hobby2', 'games'), ('hobby1', 'read'), ('zhangsan', 25)]) <class 'dict_items'> #Key value of print dictionary


6, Set default values for dictionaries

1. Use the dict.setdefault() method to set the default value for the dictionary

#Set default values for dictionaries
d1 = dict([('name','zhangsan'),('age',18),('hobby','games')])
print(d1.setdefault('name')) #zhangsan returns the corresponding value when the key value exists
print(d1.setdefault('score',90)) # 90  #When the key value does not exist, the default value is given and added to the dictionary
print(d1) # {'name': 'zhangsan', 'age': 18, 'hobby': 'games', 'score': 90}


7, Creating a formatted string with a dictionary

d1 = dict([('name','zhangsan'),('age',18),('hobby','games')])
#Use% as placeholder
print('The name is:%s,Age is:%i,Hobbies are:%s' % (d1['name'],d1['age'],d1['hobby']))
print('The name is:%(name)s,Age is:%(age)i,Hobbies are:%(hobby)s' % d1)
#Use {} as a placeholder
print('The name is:{},Age is:{},Hobbies are:{}' .format(d1['name'],d1['age'],d1['hobby']))
print('The name is:{name},Age is:{age},Hobbies are:{hobby}' .format_map(d1))


Tags: Python

Posted on Tue, 07 Jan 2020 07:24:49 -0800 by Mijii