zoukankan      html  css  js  c++  java
  • Python dict 字典

     1 #!/usr/bin/env python3
     2 # -*- coding: utf-8 -*-
     3 
     4 
     5 test_dict = {
     6     "apple": "iphone 11",
     7     "huawei": "huawei mate30 pro",
     8     "xiaomi": "xiaomi 9 pro",
     9     "alibaba": "alipay"
    10 
    11 }
    12 
    13 print(test_dict)
    14 print(test_dict.keys())
    15 print(test_dict.values())
    16 print(test_dict.items())
    17 
    18 
    19 #循环
    20 #第一种效率更高,第2种需要先转换字典
    21 for i in test_dict:
    22     print(i, test_dict[i])
    23 
    24 for i, x in test_dict.items():
    25     print(i, x)
    26 
    27 #————————————————————————————————————————————————————
    28 
    29 test_dict.setdefault("tx", "qq")                #setdefault 如果不存在 "tx" 这个字典则插入值为 赋予的,存在这查询出来
    30 print(test_dict)
    31 test_dict.setdefault("alibaba", "qq")
    32 print(test_dict)
    33 
    34 #----------------------------------------------------
    35 b = {
    36     "alibaba": "taobao",
    37     2: 3,
    38     1: 5
    39 }
    40 
    41 test_dict.update(b)                     #update 将已存在的修改,不存在的插入
    42 print(test_dict)
    43 
    44 #----------------------------------------------------
    45 
    46 c = dict.fromkeys({6, 7, 8}, "test")   #初始化一个字典,
    47 print(c)
    48 c[6] = "bbbb"                           #修改建议用一层
    49 print(c)
    50 
    51 #----------------------------------------------------
    52 
    53 
    54 
    55 
    56 #增加
    57 test_dict["google"] = "piexl"
    58 print(test_dict)
    59 
    60 #删除
    61 del test_dict["xiaomi"]             #这是python内置的通用删除方法
    62 print(test_dict)
    63 test_dict.pop("huawei")             #字典的删除方法
    64 print(test_dict)
    65 
    66 #修改
    67 test_dict["apple"] = "iphone 11 pro"
    68 print(test_dict)
    69 
    70 #查询
    71 print(test_dict["apple"])           #这种查询如果不存在则会报错
    72 print(test_dict.get("apple1"))      #get 不存在则显示none
    73 print("apple" in test_dict)         #判断是否存在
    人生天地间,忽如远行客。
  • 相关阅读:
    Elasticsearch系列(4):基本搜索
    Elasticsearch系列(3):Elasticsearch操作入门
    Elasticsearch系列(2):安装Elasticsearch(Linux环境)
    禅道之需求追踪和多角色协作流程
    Linux下Redis服务器搭建
    Sql Server 2008日志满的解决办法
    sql server2008数据库迁移的两种方案
    Linux下Jenkins服务器搭建
    Linux下RabbitMQ服务器搭建
    Linux下GitLab服务器搭建
  • 原文地址:https://www.cnblogs.com/voua/p/11654003.html
Copyright © 2011-2022 走看看