python中的字典

來源:互聯網
上載者:User
字典 :一個關聯陣列或散列表 ,可通過關鍵字索引的對象。
字典的用途:定義一個可包含多個命名欄位的對象,也可以用作快速尋找無序資料的容器
字典是python中最完善的資料類型 在程式中最常用於儲存和處理資料
如何建立:
1,在{}中放入值即可建立一個空字典;
2,使用方法 dict() 建立一個空的字典

data = {       "name" : "神行太保戴宗",       'title' :'天速星',       'age' : 45,       'price' : 490  }

要訪問字典成員 使用關鍵字索引運算子s[name] :

name = data['name'];  title = data['title'];  age = data['age'];  print(name);  print(title);  print(age);

輸出結果為:

神行太保戴宗天速星45

插入或修改對象的方法:

data['book'] = '水滸傳之梁山108將'; #插入  data['name'] = '插翅虎雷橫';  #修改  data['title'] = '天退星';

輸出結果:

水滸傳之梁山108將插翅虎雷橫天退星

字串是常用的關鍵字類型
尋找無序資料:

prices = {   'apple' :3.4,   'banana' : 4,   'orange' : 2.5,   'lemon' : 3.7,    'pear' : 1.8  }
applePrice = prices['apple'];

輸出結果:

3.4


如何判斷某個項是否是當前字典成員的:
1,使用in運算子 可測試某個內容項 是否是字典成員

if "grape" in prices:    p = prices['grape'];  else:    p= 0;  print(p);

輸出結果:

0


2,使用系統方法 get 判斷是否是字典成員

p = prices.get('grape',0);    print(p);

輸出結果:

0


擷取字典關鍵字的列表 只需要將字典轉換為列表即可:

pricelist = list(prices);

輸出結果:

['orange', 'lemon', 'pear', 'banana', 'apple']

刪除字典元素的方法 del:

del prices['pear'];

輸出結果:

{'apple': 3.4, 'banana': 4, 'lemon': 3.7, 'orange': 2.5}

總結:
1,dict字典 是什嗎?:是一個關聯性數組 或者散列表
2,建立字典:1 ,{} 2,dict()
2,字典的用途:用於快速尋找無序資料 常用於儲存和處理資料
3,使用字典關鍵字索引擷取資料
4,字典的插入和修改 :使用關鍵字索引 添加或者修改 格式 s[name] = 'data';
5,判斷元素是否存在於字典中 :1 ,in 2,get
6, 擷取字典關鍵字的方法: list 聲明為列表
6,刪除字典中的元素 :del方法

以上就是python中的字典的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.