欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python 字典(Dictionary)

程序员文章站 2024-03-23 12:45:10
...
#DictionaryType.py
#_*_ coding:UTF-8 _*_\
#!/usr/bin/python

'''
Python 字典(Dictionary)
1. 另一种可变容器模型,且可存储任意类型对象。
2. 每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 :d = {key1 : value1, key2 : value2 }
3. 键必须是唯一的,但值则不必。
4. 值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
5. 访问不存在的键,编译错误
6. 键存在,则修改键值; 键不存在,则新增元素
7. 不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住
8. 键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行
9. 
'''

print("*****************  Python 字典(Dictionary)  *************************")
dcA = {"One": "Good", 5:"Study", "Test":1314}
print("dcA => ", dcA)

print("\n" + "*****************  访问字典里的元素  *************************")
dcA = {"One": "Good", 5:"Study", "Test":1314}
print("dcA => ", dcA)
print("dcA[5]: ", dcA[5])
print("dcA[\"Test\"]: ", dcA["Test"])
#print("dcA[1]: ", dcA[1])  #Error: 没有对应的 键

print("\n" + "*****************  修改字典的元素  *************************")
dcA = {"Name": "Zhansan", "Age":20, "Sex":"Man", "Grade":"Perfect"}
print("dcA => ", dcA)

dcA["Name"] = "Lisi"
dcA["Age"] = 22
print("dcA => ", dcA)

print("\n" + "*****************  增加字典的元素  *************************")
dcA = {"Name1": "Zhansan", "Age1":20, "Sex1":"Man"}
print("dcA => ", dcA)

print("dcA[\"Name2\"] = \"Xiaofang\"")
print("键存在,则修改键值; 键不存在,则新增元素")
dcA["Name2"] = "Xiaofang"   #键存在,则修改键值; 键不存在,则新增元素
dcA["Age2"] = 25            #键存在,则修改键值; 键不存在,则新增元素
dcA["Sex2"] = "Woman"       #键存在,则修改键值; 键不存在,则新增元素
print("dcA => ", dcA)

print("\n" + "*****************  删除字典  *************************")
dcA = {"Name": "Zhansan", "Age":20, "Sex":"Man", "Grade":"Perfect"}
print("dcA => ", dcA)

print("del dcA[\"Grade\"]")
del dcA["Grade"]    #删除键和键值
print("dcA => ", dcA)

del dcA #删除字典
#print("dcA => ", dcA)
print("del dcA  #Error: 字典删除后,再次访问会报错")

print("\n" + "*****************  字典键的特性  *************************")
print("1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住")
dcA = {"Name": "Zhansan", "Age":20, "Sex":"Man", "Grade":"Perfect", "Sex":"Woman"}
print("dcA => ", dcA)

print("2)键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行")
dcB = {("Name", "Name2"): ("Zhansan", "Lisi"), "Age":20}
print("dcB => ", dcB)

dcB = {("Name", "Age"): ("Zhansan", 15), "Age":20, "Name": "Xiaofang"}
print("dcB => ", dcB)

print("\n" + "*****************  字典内置函数&方法  ********************")
dcA = {"Name": "Zhansan", "Age":20, "Sex":"Man", "Grade":"Perfect"}
print("dcA => ", dcA)
print("len(dcA) => ", len(dcA))

dcB = {("Name", "Name2"):("Zhansan", "Lisi"), "Age":20}
print("dcB => ", dcB)
print("len(dcB) => ", len(dcB))

strB = str(dcB)
print("strB = str(dcB)")
print("strB => ", strB)

#字典类型: type()
print("\n" + "字典类型")
print("type(dcB) => ", type(dcB))

#copy字典: copy()
print("\n" + "copy字典")
dcAA = dcA.copy()
print("dcAA = dcA.copy()")
print("dcAA => ", dcAA)

#创建新的字典,fromkeysdcA),dcA的键为新字典的键,值为初始值: fromkeys()
print("\n" + "创建新的字典,fromkeys(dcA),dcA的键为新字典的键,值为初始值")
dcA1 = {"Name1": "Zhansan1", "Age1":21, "Sex1":"Man1", "Grade1":"Perfect1"}
dcA2 = {"Name2": "Zhansan2", "Age2":22, "Sex2":"Man2", "Grade2":"Perfect2"}
print("dcA1 => ", dcA1)
print("dcA2 => ", dcA2)
print("dcA12 = dcA1.fromkeys(dcA2)")
dcA12 = dcA1.fromkeys(dcA2)
print("dcA12 => ", dcA12)
print("dcA21 = dcA1.fromkeys(dcA1)")
dcA21 = dcA2.fromkeys(dcA1)
print("dcA21 => ", dcA21)

#返回指定键的值: get()
print("\n" + "返回指定键的值")
print("dcA => ", dcA)
v = dcA.get("Name")
print("v = dcA.get(\"Name\")")
print("v => ", v)
v = dcA.get("NAME", 100)
print("v = dcA.get(\"NAME\", 100)")#键不存在时,返回第二个参数
print("v => ", v)

#和get()类似, 如果键不存在于字典中,将会添加键并将值设为default: setdefault()
print("\n" + "和get()类似, 如果键不存在于字典中,将会添加键并将值设为default")
print("dcA => ", dcA)
v = dcA.setdefault("Name", "Lisi")
print("v = dcA.setdefault(\"Name\", \"Lisi\")")
print("dcA => ", dcA)
print("v => ", v)
v = dcA.setdefault("NAME", "Lisi")
print("v = dcA.setdefault(\"NAME\", \"Lisi\")")#键不存在时,返回第二个参数
print("dcA => ", dcA)
print("v => ", v)

#把字典dcA的键/值对更新到dcB里: dcB.update(dcA)
print("\n" + "把字典dcA的键/值对更新到dcB里: dcB.update(dcA)")
dcA = {"Name1": "Zhansan", "Age1":21}
dcB = {"Name2": "Lisi", "Age2":22}
print("dcA => ", dcA)
print("dcB => ", dcB)
dcB.update(dcA)
print("dcB.update(dcA)")
print("dcA => ", dcA)
print("dcB => ", dcB)

#打印所有的键或键值:keys()values()
print("\n" + "打印所有的键或键值")
print("dcA => ", dcA)
print("dcA.keys() => ", dcA.keys())
print("dcA.values() => ", dcA.values())

#键是否存在字典里:in
print("\n" + "键是否存在字典里:in")
print("dcA => ", dcA)
print("\"Name\" in dcA => ", "Name" in dcA)
print("\"NAME\" in dcA => ", "NAME" in dcA)

#以列表返回可遍历的(键,值)元组数组: items()
print("\n" + "以列表返回可遍历的(键,值)元组数组: items()")
print("dcA => ", dcA)
tupleA = dcA.items()
print("tupleA = dcA.items()")
print("tupleA => ", tupleA)

#删除指定键对应的键值,返回被删除的键值,如果键不存在,则返回defaultpop(key,default)
print("\n" + "删除指定键对应的键值,返回被删除的键值,如果键不存在,则返回default: pop(key,default)")
dcA = {"Name": "Lisi", "Age":20, "Sex": "M"}
print("dcA => ", dcA)

v = dcA.pop("Age1", 33)
print("v = dcA.pop(\"Age1\", 33)")
print("v => ", v)
print("dcA => ", dcA)

v = dcA.pop("Age", 33)
print("v = dcA.pop(\"Age\", 33)")
print("v => ", v)
print("dcA => ", dcA)

#随机返回,并删除字典中的一对键/值: popitem()
print("\n" + "随机返回,并删除字典中的一对键/值(一般删除末尾): popitem()")
dcA = {"Name": "Lisi", "Age":20, "Sex": "M"}
print("dcA => ", dcA)

print("V = dcA.popitem()")
v = dcA.popitem()
print("v => ", v)
print("dcA => ", dcA)

#清空字典: clear()
print("\n" + "清空字典")
print("dcA => ", dcA)
dcA.clear()
print("dcA.clear()")
print("dcA => ", dcA)

print("\n" + "*****************  字典 无限极嵌套  ********************")
dcP = {"北京": {
                "海定区":["国贸", "CBD"],
                "朝阳区": ["北大", "清华", "圆明园"]
                },
       "深圳":{
                "南山区": ["腾讯", "TCL""安健"],
                "龙华": ["富士康", "华为"]
                },
       "赫章":{
           "城关镇":{
               "小河沟":["二中", "狮子湾", "职高", "英才中学"]},
           "野马川镇":
                {
                "平山乡":{
                   "对江村":{
                       "石板沟":{"冯家":["Fxz","Fxy"],"刘家":{"Lzg"},"朱家":{"Zzl"}},
                       "刘困塘":{"陈家", "朱家"}
                            },
                   "江南村":["七星关大桥", "夏曦纪念碑"]
                        },
               "野马川":{}
                }
             }
       }
print("dcP => ", dcP)

print("\n" + "访问嵌套字典")
print("for i in dcP[\"赫章\"][\"野马川镇\"][\"平山乡\"]:\
    print(i)")
for i in dcP["赫章"]["野马川镇"]["平山乡"]:
    print(i)

Python 字典(Dictionary)

Python 字典(Dictionary)

Python 字典(Dictionary)