# 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