Detailed usage of dictionary in Python

# dictionary
# Dictionaries are the only built-in mapping type in Python. There is no special order in the dictionary, but they are all stored in a specific key(key)Below, the keys can be numbers, strings, or even tuples

# 1. The use of dictionary
# In some cases, dictionaries are more suitable than lists:
#1、 Represents the state of a game board, each key is a tuple composed of coordinate values
#2、 Store file modification time, use file name as key;
#3、 Digital phone\Address book

#1、 Use the list to create a phone book,(The phone number is represented by a string here, and the number starting with 0 will be compiled into an octal number)
name=["A","B","C","D"]
phone=["2341","9102","3158","0142","5551"]print(phone[name.index("B")])
# This is ok, but not practical

# Second, create and use a dictionary
# Create a dictionary,The dictionary is composed of multiple keys and their corresponding values.-Value pairs are separated by colons, items are separated by commas, and the dictionary is enclosed by braces. Empty dictionary by{}composition
# The keys in the dictionary are unique, but the values are not unique
phonebook={"Alice":"2431",'Beth':'9102','Cecil':'3258'}

#1、 dict function, you can use dict function, through other mapping(Such as other dictionaries)or(Key, value)A dictionary of pairs of sequences
items=[('name','Gumby'),('age',42)]
d=dict(items)print(d)print(d['name'])

# The dict function can also create a dictionary through keyword arguments
a=dict(name="CY",num=42)print(a['name'])

#2、 Basic dictionary operation
# Most operations are similar to sequences

# Returns the number of key-value pairs in the dictionary
print(len(a))
# Normal index
a=dict(name="CY",num=42)print(a["name"])

# Assign a value to the key in the dictionary
a["name"]="Challenger"print(a)

# del delete key
del a["name"]print(a)

# Use in to detect whether the key exists in the dictionary
print("num"in  a)

# Difference from the list
# Key type:字典的Key type不一定为整形数据,键可以是任意不可变类型,比如浮点类型(Real type), String or meta-rent
# Automatically added:Even if the key does not exist in the dictionary at first, you can assign a value to it and the dictionary will create a new item. and(Without using the append method or other similar operations)Cannot associate a value to an index outside the range of the list
# The expression key in dictionary finds the key, not the value. The expression value in list is used to find the value, not the index.
# The membership of the check key in the dictionary is higher than the membership of the check value in the list. The larger the data structure, the more obvious the efficiency gap between the two
# Dictionary example
# A simple database
# The dictionary uses names of people as keys. Each person is represented by another dictionary whose keys'phone'with'addr'分别表示他们的电话号码with地址
people={'Alice':{'phone':'2341','addr':'Fpp driver 23'},'Beth':{'phone':'9102','addr':'Bar street 42'},'Cecil':{'phone':"3158",'addr':'Baz avenue 90'}}

# The descriptive label used for the address of the phone number will be used in the printout
lable={'phone':'phone number','addr':'address'}

name=input('Name: ')
# Find phone number or address?
request=input('Phone number(p) or address(a)?')
# Use the correct key value
if request=='p':
 key='phone'if request=='a':
 key='addr'
# Only print information if the name is a valid key value in the dictionary
if name in people:print("%s's %s is %s."%(name,lable[key],people[name][key]))
#4 Dictionary method
#1、 clear method
# The clear method clears all items in the dictionary. This is an in-situ operation, similar to(list.sort)So no return value(Or return None)
d={}
d['name']='CY'
d['age']=23print(d)
returned_value=d.clear()print(d)print(returned_value)
# The meaning of using clear is to really empty the original dictionary
# Situation One,Associating x with an empty dictionary can clear x, but will not affect y, and y is also associated with the original dictionary.
x={}
y=x
x['key']='value'print(y)
x={}print(x)print(y)
# Situation two,Use the clear method to clear the original dictionary
x1={}
y1=x1
x1["key"]="value"print(y1)
x1.clear()print(x1)print(y1)
#2、 The copy method returns a new dictionary with the same key-value pairs(This method implements shallow copy, because the value itself is the same, not a copy),The dictionary copied using copy, if the value is not affected, if modified(Add, delete)Value, the original dictionary will also change

x={'username':'admin','machines':['foo','bar','baz']}
y=x.copy()
y['username']='mlh'
y['machines'].remove('bar')print(y)print(x)

# To avoid the above problems, you can use the deepcopy function
from copy import deepcopy
d={}
d['name']=['Alfred','Bertrand']
c=d.copy()
dc=deepcopy(d)
d['name'].append('Clive')print(c)print(dc)

#3、 The fromkeys method uses the given keys to create a new dictionary, each key corresponds to a None
print({}.fromkeys(['name','age']))
# The above method uses an empty dictionary, creating another dictionary is a bit redundant, you can use the dict method directly
print(dict.fromkeys(['name','age']))
# You can also specify default values
print(dict.fromkeys(['name','age'],'(unknown)'))

#4、 The get method is a very loose way to access the dictionary. If you do not use get, you will get an error when accessing items that do not exist in the dictionary,Will return none
d={}print(d.get('name'))
# Can also be customized"Defaults"print(d.get('name',"N/A"))
# If the key exists, get is used in the same way as a normal dictionary query
d['name']='CY'print(d.get('name'))
# Use the get method to realize the function of the phone book
people={'Alice':{'phone':'2341','addr':'Fpp driver 23'},'Beth':{'phone':'9102','addr':'Bar street 42'},'Cecil':{'phone':"3158",'addr':'Baz avenue 90'}}

lable={'phone':'phone number','addr':'address'}

name=input('Name: ')

request=input('Phone number(p) or address(a)?')if request=='p':
 key='phone'if request=='a':
 key='addr'

person=people.get(name,{})
lable=lable.get(key,key)
result=person.get(key,'not available')print("%s's %s is %s."%(name,lable,result))
#5、 items
# The item method returns all the items in the dictionary in a list, and there is no specific order when returning
# 3. x inside, iteritems()And viewitems()Both methods have been abolished, and items()The result is and 2.x inside viewitems()Consistent. At 3.Use items in x()Replace iteritems(), Can be used for for to loop through.
d={'title':'ppp','name':'ccc'}print(d.items())

#6、 keys()Return the keys in the dictionary as a list
print(d.keys())

#7、 The pop method is used to get the value corresponding to a given key, and then remove this key-value pair from the dictionary
d1={'aasd':"sadad",'asdasd':"sadsadad"}print(d1.pop('aasd'))print(d1)

#8、 popitem
# The popitem method is similar to list.pop,The latter pops up the last element of the list. But the difference is that popitem pops up random items, because there is no last element in the dictionary, this method is suitable for removing and processing items one by one.(No need to get the list of keys first, so it's very efficient)
d2={'a':'b',"c":'d'}print(d2.popitem())print(d2)

#9、 setdefault
# setdefault is similar to get in a way, can get the value related to a given key, setdefault can also set the corresponding key value when the dictionary does not contain the given key,If the key value exists, the original key value will not be modified
d3={}
d3.setdefault('name','None')print(d3)
d3['name']='CY'print(d3.setdefault('name','None'))

#10、 update
# The update method can use one dictionary to update another dictionary,If the key value exists, it will be overwritten, if it does not exist, it will be added
d={'title':'sasdadadad',"url":"asdasdadsad","change":'asdasdada'}
a={'title':"a"}
d.update(a)print(d)

#11、 values,Used to return the value in the current dictionary
d={}
d[1]=1
d[2]=2print(d.values())
# Dictionary format string
# After each conversion specifier, you can add a key(Enclosed in parentheses), Followed by a description element
phonebook={'Beth':'9102','Alice':'1111','tom':'1551'}print("tom's phoneNum is %s"% phonebook["tom"])print("tom's phoneNum is %(tom)s"% phonebook)

# Except for the added string key, the conversion specifier works as before. When using a dictionary in this way, any number of conversion specifiers can be used as long as all the given keys can be found in the dictionary.
# This type of string formatting is very useful in the template system
template="""<html><head><title>%(title)s</title></head><body><h1>%(title)s</h1><p>%(text)s</p></body>"""

data={"title":"My Home Page","text":"Welcome to my home page!"}print(template % data)

Recommended Posts

Detailed usage of dictionary in Python
The usage of wheel in python
Usage of os package in python
The usage of tuples in python
The usage of Ajax in Python3 crawler
Detailed usage of Python virtual environment venv
MongoDB usage in Python
The meaning and usage of lists in python
Detailed explanation of the usage of Python decimal module
Subscripts of tuples in Python
Detailed explanation of Python web page parser usage examples
Summary of logarithm method in Python
Detailed explanation of python backtracking template
Analysis of usage examples of Python yield
Use of Pandas in Python development
Detailed implementation of Python plug-in mechanism
Detailed explanation of python sequence types
Python3 dictionary
Detailed sorting algorithm (implemented in Python)
Detailed use of nmcli in CentOS8
Use of numpy in Python development
Simple usage of python definition class
Description of in parameterization in python mysql
Understanding the meaning of rb in python
Implementation of JWT user authentication in python
Detailed explanation of Python IO port multiplexing
Detailed analysis of Python garbage collection mechanism
Analysis of glob in python standard library
Method of installing django module in python
Detailed explanation of -u parameter of python command
How to sort a dictionary in python
Detailed explanation of Python guessing algorithm problems
Knowledge points of shell execution in python
Functions in python
7 features of Python3.9
What is the function of adb in python
Detailed explanation of the principle of Python super() method
Detailed explanation of python standard library OS module
The usage of several regular expressions in Linux
Python implements the shuffling of the cards in Doudizhu
The usage of several regular expressions in Linux
Can the value of the python dictionary be modified?
Detailed explanation of how python supports concurrent methods
The usage of several regular expressions in Linux
The consequences of uninstalling python in ubuntu, very
Detailed explanation of data types based on Python
Example of feature extraction operation implemented in Python
Detailed examples of using Python to calculate KS
03. Operators in Python entry
Python3 built-in module usage
Detailed explanation of the principle of Python function parameter classification
Detailed explanation of the principle of Python timer thread pool
Join function in Python
12. Network Programming in Python3
print statement in python
Detailed explanation of the implementation steps of Python interface development
How does python call the key of a dictionary
Installation and use of GDAL in Python under Ubuntu
Detailed Python loop nesting
How to understand the introduction of packages in Python
Basics of Python syntax