標籤:python 字典操作
字典一種key - value 的資料類型,使用就像我們上學用的字典,通過筆劃、字母來查對應頁的詳細內容。
文法:
#!/usr/bin/env python# -*- coding:utf-8 -*-info = { ‘stu1101‘: "TengLan Wu", ‘stu1102‘: "LongZe Luola", ‘stu1103‘: "XiaoZe Maliya",}print (info) 執行結果:{‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1102‘: ‘LongZe Luola‘, ‘stu1101‘: ‘TengLan Wu‘}
字典的特性:
dict是無序的
key必須是唯一的,so 天生去重
增加
>>> info["stu1104"] = "蒼井空">>> info{‘stu1102‘: ‘LongZe Luola‘, ‘stu1104‘: ‘蒼井空‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1101‘: ‘TengLan Wu‘}
修改
>>> info[‘stu1101‘] = "武藤蘭">>> info{‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1101‘: ‘武藤蘭‘}
刪除
>>> info{‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1101‘: ‘武藤蘭‘}>>> info.pop("stu1101") #標準刪除姿勢‘武藤蘭‘>>> info{‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘}>>> del info[‘stu1103‘] #換個姿勢刪除>>> info{‘stu1102‘: ‘LongZe Luola‘}>>> >>> >>> >>> info = {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘}>>> info{‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘} #隨機刪除>>> info.popitem()(‘stu1102‘, ‘LongZe Luola‘)>>> info{‘stu1103‘: ‘XiaoZe Maliya‘}
尋找
>>> info = {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘}>>> >>> "stu1102" in info #標準用法True>>> info.get("stu1102") #擷取‘LongZe Luola‘>>> info["stu1102"] #同上,但是看下面‘LongZe Luola‘>>> info["stu1105"] #如果一個key不存在,就報錯,get不會,不存在只返回NoneTraceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: ‘stu1105‘
多級字典嵌套及操作
av_catalog = { "歐美":{ "www.youporn.com": ["很多免費的,世界最大的","品質一般"], "www.pornhub.com": ["很多免費的,也很大","品質比yourporn高點"], "letmedothistoyou.com": ["多是自拍,高品質圖片很多","資源不多,更新慢"], "x-art.com":["品質很高,真的很高","全部收費,屌比請繞過"] }, "日韓":{ "tokyo-hot":["品質怎樣不清楚,個人已經不喜歡日韓範了","聽說是收費的"] }, "大陸":{ "1024":["全部免費,真好,好人一生平安","伺服器在國外,慢"] }}av_catalog["大陸"]["1024"][1] += ",可以用爬蟲爬下來"print(av_catalog["大陸"]["1024"])#ouput [‘全部免費,真好,好人一生平安‘, ‘伺服器在國外,慢,可以用爬蟲爬下來‘]
其它姿勢
#values>>> info.values()dict_values([‘LongZe Luola‘, ‘XiaoZe Maliya‘])#keys>>> info.keys()dict_keys([‘stu1102‘, ‘stu1103‘])#setdefault>>> info.setdefault("stu1106","Alex")‘Alex‘>>> info{‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘}>>> info.setdefault("stu1102","龍澤蘿拉")‘LongZe Luola‘>>> info{‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘}#update >>> info{‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘}>>> b = {1:2,3:4, "stu1102":"龍澤蘿拉"}>>> info.update(b)>>> info{‘stu1102‘: ‘龍澤蘿拉‘, 1: 2, 3: 4, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘}#itemsinfo.items()dict_items([(‘stu1102‘, ‘龍澤蘿拉‘), (1, 2), (3, 4), (‘stu1103‘, ‘XiaoZe Maliya‘), (‘stu1106‘, ‘Alex‘)])#通過一個列表產生預設dict,有個沒辦法解釋的坑,少用吧這個>>> dict.fromkeys([1,2,3],‘testd‘){1: ‘testd‘, 2: ‘testd‘, 3: ‘testd‘}
迴圈dict
#方法1for key in info: print(key,info[key])#方法2for k,v in info.items(): #會先把dict轉成list,資料裡大時莫用 print(k,v)
本文出自 “小菜鳥” 部落格,請務必保留此出處http://baishuchao.blog.51cto.com/12918589/1935077
python 字典操作