Python字典详解

字典特征

1. 字典使用dict表示;

2. 字典基本结构;

info = {
  "k1": "v1",   # 键值对
  "k2": "v2"
}

3. 列表、字典不能作为字典的key;

4. value值可是任何值,并且可以无线嵌套;

5. 字典是无序的;

6. 从字典取值要通过索引key值去取值;(字典是无序的,所以不能通过索引取值);

info = {
     "k1": 18,
     2: True,
     "k3": [
         11,
         [],
         (),
         22,
         33,
         {
             'kk1': 'vv1',
             'kk2': 'vv2',
             'kk3': (11,22),
         }
     ],
     "k4": (11,22,33,44)
 }
 v = info['k1']
 print(v)
 v = info[2]
 print(v)
 v = info['k3'][5]['kk3'][0]
 print(v)

7. 字典的值可以被删除

 del info['k1']
 del info['k3'][5]['kk1']
 print(info)

8. 关于字典的for循环

 for item in info   #默认循环的key

 for item in info.keys    #指定循环key

 for item in info.values   #指定循环value

 for k,v in info.items   #指定循环key和value 

字典的功能总结 

1. 为字典的key增加index

dic = {
    "k1": 'v1',
    "k2": 'v2'
}

for i, v in enumerate(dic, 1):
    print(i, v)

2. 根据序列,创建字典,并指定统一的值

v = dict.fromkeys(["k1",123,"999"],123)
print(v)

3. 根据Key获取值,key不存在时,可以指定默认值(None)

v = dic['k11111']
print(v)            #直接通过key值去获取值,如果key值不存在会报错;
v = dic.get('k1',111111)
print(v)       #推荐使用get的方式获取值,没找到会返回设置的值;

4. 删除并获取值

dic = {
    "k1": 'v1',
    "k2": 'v2'
}
v = dic.pop('k1',90)   #如果没有找到要删除的对象,则会返回设置的值90;
print(dic,v)
k,v = dic.popitem()
print(dic,k,v)

5. 设置值

已存在,不设置,获取当前key对应的value值
不存在,设置,获取新设置key对应的value值
dic = {
    "k1": 'v1',
    "k2": 'v2'
}
v = dic.setdefault('k1111','123')
print(dic,v)

6. 更新

dic = {
    "k1": 'v1',
    "k2": 'v2'
}
dic.update({'k1': '111111','k3': 123})
print(dic)
dic.update(k1=123,k3=345,k5="asdf")
print(dic)

7. 为字典增加键值对的普通方法

dic = {}
dic["hello"] = {}
dic["word"] = []
dic["hello"]["good"] = {}
print(dic)


字典应用阶段编程练习 多级大纲查看新增交互程序写法一

#!/bin/bash/env python
# -*- conding: utf-8 -*-

db = {}
path = []

while True:
    temp = db
    for item in path:
        temp = temp[item]
    print("=============================================================================")
    print("当前所有子节点是:",list(temp.keys()))
    print("=============================================================================")
    name = input(" 1:增加节点;\n 2:查看节点;\n b:退回上一级;\n q:退出所有;\n\n请输入你的选择>>>>>>")
    if name == "1":
        x = input("请输入要添加的节点名称:")
        if x in temp:
            print("节点已经存在!")
        else:
            temp[x] = {}
    elif name == "2":
        y = input("请输入要查看的子节点名称:")
        if y in temp:
            path.append(y)
        else:
            print("输入的子节点不存在")
    elif name.lower() == "b":
        if path:
            path.pop()
    elif name.lower() == "q":
        break
    else:
        print("输入错误,请重新输入!!!")

 

 

字典应用阶段编程练习 多级大纲查看新增交互程序写法二

#!/bin/bash/env python
# -*- conding: utf-8 -*-

dic = {
    "植物": {
        "草本植物": ["风信子", "紫罗兰", "长寿花", "牡丹", "向日葵"],
        "木本植物": ["梅花", "茉莉花", "梅花", "桂花", "月季"],
        "水生植物": ["荷花", "芦苇", "香蒲", "", "水葱"]
    },
    "动物": {
        "两栖动物": ["乌龟", "青蛙", "", "蜥蜴", "娃娃鱼"],
        "禽类": ["乌鸡", "白鸡", "黑鸡", "黄鸡", "黑鸡"],
        "哺乳动物": ["老虎", "猴子", "斑马", "大象", "老鼠"]
    }
}

go = True

while go:
    print("#############################")
    li1 = []
    for i, v in enumerate(dic, 1):
        print(i, v)
        li1.append(v)
    print("=============================")
    print("提示:i编辑,q退出程序,数字选择进入对应的下一级菜单")
    ui1 = input("请输入你的选择:")
    if ui1.isdecimal():
        ui1 = int(ui1)
        if 1 <= ui1 <= i:
            pass
        else:
            print("输入序号超出范围,请重新输入!")
            continue
    elif ui1.isalpha():
        if ui1.lower() == "q":
            go = False
            break
        elif ui1.lower() == "i":
            i1 = input("此处增加一级节点,请输入要增加的节点:")
            dic[i1] = {}
            continue
        else:
            print("输入错误,请重新输入!")
            continue
    else:
        print("输入错误,请重新输入!")
        continue

    while go:
        print("#############################")
        li2 = []
        for i, v in enumerate(dic[li1[ui1 - 1]], 1):
            print(i, v)
            li2.append(v)
        print("=============================")
        print("提示:i编辑,q退出程序,b回退上一级,数字选择进入对应的下一级菜单")
        ui2 = input("请输入你的选择:")
        if ui2.isdecimal():
            ui2 = int(ui2)
            if 1 <= ui2 <= i:
                pass
            else:
                print("输入序号超出范围,请重新输入!")
                continue
        elif ui2.isalpha():
            if ui2.lower() == "b":
                li1.clear()
                break
            elif ui2.lower() == "q":
                go = False
                break
            elif ui2.lower() == "i":
                i2 = input("此处增加二级节点,请输入要增加的节点:")
                dic[li1[ui1 - 1]][i2] = []
                continue
            else:
                print("输入错误,请重新输入!")
                continue
        else:
            print("输入错误,请重新输入!")
            continue

        while go:
            print("#############################")
            for v in dic[li1[ui1 - 1]][li2[ui2 - 1]]:
                print(v)
            print("=============================")
            print("提示:i编辑,q退出程序,b回退上一级")
            ui3 = input("请输入你的选择:")
            if ui3.isalpha():
                if ui3.lower() == "b":
                    del li2[:]
                    break
                elif ui3.lower() == "q":
                    go = False
                    break
                elif ui3.lower() == "i":
                    i3 = input("此处增加三级节点,请输入要增加的节点:")
                    dic[li1[ui1 - 1]][li2[ui2 - 1]].append(i3)
                    continue
                else:
                    print("输入错误,请重新输入!")
                    continue
            else:
                print("输入错误,请重新输入!")
                continue
posted @ 2019-12-25 09:54  IamJet  阅读(502)  评论(0编辑  收藏  举报