文章目錄
- 一、編譯環境和編譯器
- 二、字典
- 1.定義字典,獲取字典關鍵字、值、物件
- 2.字典的操作:增、刪、改、查、復制和創建
一、編譯環境和編譯器
ArcGIS10.6:Python2.7.14 32-bit
編譯器:Visual Studio Code
二、字典
1.定義字典,獲取字典關鍵字、值、物件
代碼如下(示例):
# encoding=utf-8
#定義字典{key:value}
dicA={"name":"Xiao Ming","age":14,"high":167,"other":""}
print(dicA)
print(len(dicA))#列印字典長度
#獲取關鍵字、值、物件
print(dicA.keys())#列印字典關鍵字
print(type(dicA.keys()))#字典關鍵字型別,list
print(dicA.values())#列印值
print(type(dicA.values()))#字典值型別,list
print(dicA.items())#列印物件
print(type(dicA.items()))#字典物件型別,list
print("----------0")
#通過回圈獲取,以獲取物件為例
for item in dicA.items():
print(item)
print("----------1")
#根據關鍵字獲取值
print(dicA.get("name"))#根據關鍵字”name"獲取值Xiao Ming
dicA.get("name")#當獲取的關鍵字在原字典中不存在時,get()會回傳默認值,但不改變原字典,
print(dicA)
print(dicA.setdefault('name'))#根據關鍵字”name"獲取名字Xiao Ming
dicA.setdefault('grades')#當獲取的關鍵字在原字典中不存在時,setdefaul()t會回傳默認值None并更新字典
print(dicA)
列印結果:
{'high': 167, 'age': 14, 'other': '', 'name': 'Xiao Ming'}
4
['high', 'age', 'other', 'name']
<type 'list'>
[167, 14, '', 'Xiao Ming']
<type 'list'>
[('high', 167), ('age', 14), ('other', ''), ('name', 'Xiao Ming')]
<type 'list'>
----------0
('high', 167)
('age', 14)
('other', '')
('name', 'Xiao Ming')
----------1
Xiao Ming
{'high': 167, 'age': 14, 'other': '', 'name': 'Xiao Ming'}
Xiao Ming
{'high': 167, 'age': 14, 'other': '', 'grades': None, 'name': 'Xiao Ming'}
2.字典的操作:增、刪、改、查、復制和創建
dicA={'high': 167, 'age': 14, 'other': '', 'grades': None, 'name': 'Xiao Ming'}
#字典的操作
#增
dicA["sex"]="boy"#用[]直接添加字典關鍵字和值,且增加在字典尾部
print(dicA)#列印增加后字典
dicB={"class":1,34:"ge"}
dicA.update(dicB)#將dicB更新到dicA中
print(dicA)#列印更新后結果
print("----------2")
#刪
del dicA["other"]#通過del洗掉關鍵詞和值
print(dicA)#列印洗掉后字典
dicA.pop("age")#索引并洗掉關鍵字為“age"的鍵值對
print(dicA)#列印pop后字典
dicA.popitem()#索引并洗掉字典最新加入的鍵值對
print(dicA)#列印popitem后結果
print("----------3")
#改
dicA["sex"]="girl"#通過關鍵字將性別改為girl,它會覆寫原來值
print(dicA)#列印改后字典
print("----------4")
#查
print dicA.has_key("sex")#查詢字典中是否存在關鍵字sex
print("----------5")
#字典的復制
print(dicA.copy())#列印復制后字典
print("----------6")
#創建新字典
dic1={}#新建一個空的字典
dic2=dic1.fromkeys(("hair","leg"),"long")#對空的字典添加"hair"和“leg"兩個關鍵值,并將值都賦為long
print(dic2)#列印新建字典
#清除
dic2.clear()#清除dic2
print(dic2)
列印結果:
{'name': 'Xiao Ming', 'age': 14, 'sex': 'boy', 'high': 167, 'grades': None, 'other': ''}
{34: 'ge', 'name': 'Xiao Ming', 'age': 14, 'sex': 'boy', 'high': 167, 'grades': None, 'other': '', 'class': 1}
----------2
{34: 'ge', 'name': 'Xiao Ming', 'age': 14, 'sex': 'boy', 'high': 167, 'grades': None, 'class': 1}
{34: 'ge', 'name': 'Xiao Ming', 'sex': 'boy', 'high': 167, 'grades': None, 'class': 1}
{'name': 'Xiao Ming', 'sex': 'boy', 'high': 167, 'grades': None, 'class': 1}
----------3
{'name': 'Xiao Ming', 'sex': 'girl', 'high': 167, 'grades': None, 'class': 1}
----------4
True
----------5
{'high': 167, 'class': 1, 'grades': None, 'name': 'Xiao Ming', 'sex': 'girl'}
----------6
{'hair': 'long', 'leg': 'long'}
{}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/271346.html
標籤:python
上一篇:Python模塊匯入規范
