程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Development -- 15 dictionary type built-in method

編輯:Python

List of articles

    • One . purpose
    • Two . Define the way
    • 3、 ... and . Data type conversion
    • Four . Common operations + Built-in methods
    • Priority operation (*********)
      • 1. according to key Value , It is advisable to save
      • 2、 length : .len( )
      • 3. Members of the operation in and not in
      • 4. Delete del, .pop( ), .popitem
      • 5. Value : key .keys( ), value .values( ), Key value pair .items( )
      • 6. Value .get( ) --->( seek )
    • Operations that need to be mastered (****)
      • 1. to update .update( )
      • 2. Empty .clear( )
      • 3. initialization ( build ) A dictionary template .fromkeys( )
      • 4. Add and return the value .setdefaul( )
    • 5、 ... and . summary
      • You can store multiple values
      • disorder , The value is determined by "key" Take the corresponding "value"
      • Variable type ---> must not hash type
  • {'name': 'mm', 'age': '12'} # If so, don't add

One . purpose

  • With key : value There are multiple values in the form of
  • advantage : Access is fast , Each value has a corresponding key

Two . Define the way

  • stay “{ }” Separate multiple elements with commas inside
  • The format is “key : value”, among key Must be of immutable type , value It can be any type
  • Dictionary type corresponds to " factory " Namely dict
dic = {
"name" : "mm","age" : 18}
# The operation behind it is 
dic = dict(name = "mm", age = 18)

3、 ... and . Data type conversion

res=dict([("k1",1111),("k2",2222),("k3",3333)])
print(res)
res=dict(x=111,y=222,z=333)
print(res)
# ".fromkeys" The method is below " The method that needs to be mastered " It introduces in detail 
res={
}.fromkeys(["name","age","gender"],None)
print(res)
=============================
info = [
["name","mm"],
("age",22),
["gender","male"]
]
res = dict(info) #dict Convert list characters directly to dictionary characters 
print(res)
{
'name': 'mm', 'age': 22, 'gender': 'male'}
================================
# Mode one :
keys = ["name","age","gender"]
value=None
d={
}
for k in keys:
d[k]= None
print(d)
{
'name': None, 'age': None, 'gender': None}
# Mode two :
keys = ["name","age","gender"]
value=None
d={
}.fromkeys(keys,value)
{
'name': None, 'age': None, 'gender': None}
# Mode three :
keys = ["name","age","gender"]
d={
}.fromkeys(keys,None) # By default :value=None
{
'name': None, 'age': None, 'gender': None}

Four . Common operations + Built-in methods

Priority operation (*********)

1. according to key Value , It is advisable to save

# Press "key" Save a value 
dic = {
"name":"mm"}
dic["age"] = 22
print(dic) # {'name': 'mm', 'age': 22}
# Value can also be taken , Change value 
dic["age"] = 18
dic["name"] = dic["name"].upper()
print(dic) #{'name': 'mm', 'age': 18}

2、 length : .len( )

  • The statistics are key The number of
  • If there is key Same key value pair , Then the main thing to enter later
# With "key" To decide the number 
dic = {
"name":"mm","age":22,"sex":"man"}
print(len(dic)) # 3
# There are two "age", Mainly in the back ( It's equivalent to that you changed "age" It's worth the same )
dic = {
"name":"mm","age":22,"sex":"man","age":18}
print(dic) #{'name': 'mm', 'age': 18, 'sex': 'man'}
==========================================
dic = {
"name":"mm","age":"12","name":"kk"}
print(len(dic["name"]))
2

3. Members of the operation in and not in

  • Judge whether it's dictionary or not key
dic = {
"name":"mm","age":22,"sex":"man"}
print("name" in dic) #True
print("age" not in dic) #False

4. Delete del, .pop( ), .popitem

  • del : Delete directly " who ", Universal universal delete , It does not support assignment Syntax , The assignment will report an error
  • .pop() : according to key To delete , The value returned is key Corresponding value
  • .popitem() : No parameter , Randomly delete a key value , Returns a tuple , The first value in the tuple is key, The second value corresponds to value
# "del"
dic = {
"name":"mm","age":22,"sex":"man"}
del dic["name"]
print(dic) #{'age': 22, 'sex': 'man'}
# ".pop", Will return to deleted "value"
res = dic.pop('age')
print(res) #22
print(dic) #{'sex': 'man'}
# ".popitem" The value returned is a tuple , ("key", "value")
dic = {
"name":"mm","age":22,"sex":"man"}
res = dic.popitem()
print(res) #('sex', 'man')
print(dic) #{'name': 'mm', 'age': 22}

5. Value : key .keys( ), value .values( ), Key value pair .items( )

  • .keys() : Take only key
  • .values() : Take only value
  • .items() : Both key, And take value
  • Add for Loop combination
dic = {
"name":"mm","age":22,"sex":"man"}
# ".keys()"
list=[]
print(dic.keys()) #dict_keys(['name', 'age', 'sex'])
for k in dic.keys():
list.append(k)
print(list) #['name', 'age', 'sex']
# ".values()"
list2 = []
print(dic.values()) #dict_values(['mm', 22, 'man'])
for v in dic.values():
list2.append(v)
print(list2) #['mm', 22, 'man']
# ".items()"
l1 = []; l2 = []
print(dic.items()) #dict_items([('name', 'mm'), ('age', 22), ('sex', 'man')])
for k,v in dic.items():
l1.append(k)
l2.append(v)
print(l1) #['name', 'age', 'sex']
print(l2) #['mm', 22, 'man']

ps : Python2 In the middle of key .keys( ), value .values( ), Key value pair .items( ) It's directly the result of the list output , It takes up a lot of space , and Python3 It's like an old hen , Take one if you want

# "Python2" Dictionary value in 
>>> dic = {
"name":"mm","age":22,"sex":"man"}
>>>
>>> dic.keys()
['name', 'age', 'sex']
>>>
>>> dic.values()
['mm', 22, 'man']
>>>
>>> dic.items()
[('name', 'mm'), ('age', 22), ('sex', 'man')]

6. Value .get( ) —>( seek )

  • It's mentioned above that you can use “dic[key]” In this way, the value is taken , But I can't find any mistakes
  • .get() : Parameter is key, No return found None, Better fault tolerance
dic = {
"name":"mm","age":22,"sex":"man"}
# "dic[key]" No error found 
res = dic["xxxx"]
print(res) # Report errors 
# ".get()" Found return "value", No return found "None"
res = dic.get("name")
print(res) #mm
res = dic.get("xxxx")
print(res) #None

Operations that need to be mastered (****)

1. to update .update( )

  • Update is the modification or addition of key value pairs
  • It's like a piece of software , The new version is based on the old version modify BUG perhaps Add function
  • For old dictionaries , Update means : In the new dictionary and not in the old dictionary, add , The new and the old cover
dic = {
"name":"mm","age":22}
# Revised "age", Added "sex"
res = dic.update({
"age":18,"sex":"man"})
print(dic) #{'name': 'mm', 'age': 18, 'sex': 'man'}

2. Empty .clear( )

dic = {
"name":"mm","age":22,"sex":"man"}
dic.clear()
print(dic) #{}

3. initialization ( build ) A dictionary template .fromkeys( )

  • The first parameter is key, The latter parameter is value
  • grammar : {}.fromkeys(['name','age','sex'],'xxxxxx')
# Don't use ".fromkeys" Build a template 
good_info={

'name':None,
'price':None,
'count':None
}
# Use ".fromkeys()" Build a template 
dic = {
}.fromkeys(['name','age','sex'],None)
print(dic) #{'name':None,'age':None,'sex':None}
  • Example
 Use "for" loop
list1=['name','price','count']
dic={
}
for x in list1:
dic[x]=None
print(dic) #{'name': None, 'price': None, 'count': None}
Use ".fromkeys()" Direct realization
dic = {
}.fromkeys(list1,None)
print(dic) #{'name': None, 'price': None, 'count': None}
# Add product information 
'mac' 20000 10 # Commodity information 
dic['name']='mac' # Add product information to the template 
dic['price']=20000 # Price 
dic['count']=10 # Number 

4. Add and return the value .setdefaul( )

  • If there is something to add to the dictionary key, No modification , And back to key Corresponding primary value
  • If there is nothing to add to the dictionary key, Then add , And return the added key Corresponding new value
# Add existing "key"
dic={
'name':'mm','age':22}
res=dic.setdefault('name','mm')
print(' Return value :',res) # Return value : mm
print(dic) #{'name': 'mm', 'age': 22}
# Add nonexistent "key"
res=dic.setdefault('sex','man')
print(' Return value :',res) # Return value : man
print(dic) #{'name': 'mm', 'age': 22, 'sex': 'man'}
# If key Yes , Don't add , Add if not 
dic = {
"name":"mm","age":"12"}
if "name" in dic:
... # ... be equal to pass
else:
dic["name"] = "mm"
print(dic)
# {'name': 'mm', 'age': '12'} # If so, don't add 
{
'nam': 'mm', 'age': '12', 'name': 'mm'} # Add if not 'name': 'mm'

5、 ... and . summary

  • You can store multiple values

  • disorder , The value is determined by “key” Take the corresponding “value”

  • Variable type —> must not hash type

“name” in dic:
… # … be equal to pass
else:
dic[“name”] = “mm”
print(dic)

{‘name’: ‘mm’, ‘age’: ‘12’} # If so, don't add

{‘nam’: ‘mm’, ‘age’: ‘12’, ‘name’: ‘mm’} # Add if not ‘name’: ‘mm’


## 5、 ... and . summary
- ### You can store multiple values
- ### disorder , The value is determined by "key" Take the corresponding "value"
- ### Variable type ---> must not hash type

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved