• 基础数据类型初识(三)字典


     字典 :python 中非常重要的数据类型,在python中唯一一个映射的数据类型

    可变与不可变 不可变数据类型:int str bool tuple可变数据类型:list,dic,set dic = {"name":"alex","name_list":["小黑","changjiang"]} key 是唯一的 且 是不可变数据类型value 是任意数据类型 在3.5版本(包括)之前,字典是无序的3.6版本(包括),是有序的放大量的数据类型,且关联性较强 字典功能 1.增(1)通过key找value,有key 就覆盖。无key 就添加 dic = {"name":"alex","name_list":["小黑","changjiang"]}dic["name2"] = "xue"print(dic) (2)setdefault,有key 不变,没有key才添加dic.setdefault("hobby")print(dic) dic.setdefault("hobby","hsjdh") print(dic) dic.setdefault("name","小白") print(dic) 2.删除(1)pop 按key删除,有返回值,并且如果字典中没有此key,可设置返回值ret = dic.pop("name")print(ret)print(dic) ret = dic.pop("name4","没有此键")print(ret) (2)clear()清空dic.clear()print(dic) (3)del 删除字典,删除键值对,并且在内存中找不到这个字典del dicprint(dic) del dic["name"]print(dic) (4)popitem 随机删除,删除内容可以返回,返回值是元组类型ret = dic.popitem()print(ret)print(dic) 3.改(1)dic["key"] = value有key就覆盖,无key就添加 (2)update 将dic的键值对,覆盖,添加到dic2中,dic不变 dic2 = {"name":"e","habby":"paly"} dic = {"name":"alex","name_list":["小黑","changjiang"]} dic2.update(dic)print(dic)print(dic2) 4.查(1)print([dic["name"]])print(dic) (2)print(dic.get("name"))print(dic.get("name2"))print(dic.get("name2","没有此键值对")) 取所有的键,所有的值,所有的键值对第一种办法: keys = dic.keys() print(keys) values = dic.values() print(values) items = dic.items() print(items) 第二种: for keys in dic: print(keys) for keys in dic.keys(): print(keys) for values in dic.values(): print(values) for keys,values in dic.items(): print(keys,values) for k in dic: print(k,dic[k]) 第三种: # dic = { # 'name':'金鑫', # 'name_list':[1,2,3,'李杰'], # 1:{ # 'python10':['小黑','萌哥'], # '老男孩':{'name':'oldboy','age':56} # } # } #1,[1,2,3,'李杰']追加'wusir' #2, ['小黑','萌哥'] 小黑 萌哥中间 插入一个花哥 #3, {'name':'oldboy','age':56} 添加一个键值对,hobby:男人 # dic["name_list"].append("wusir") # print(dic) # dic[1]["python10"].insert(1,"花哥") # print(dic) # dic[1]["老男孩"]["habby"]= "男人" # print(dic)
  • 相关阅读:
    Spring Cloud Gateway 使用
    Spring Cloud Stream 整合 RabbitMQ
    机器学习知识总结---1、回归和分类是可以相互转换的
    23个适合Java开发者的大数据工具和框架
    serilog Getting Started
    NLog.Targets.ElasticSearch
    RollingFileAppender bufferSize is not working? Here is an alternative
    go微服务示例(k8s istio grpc swagger postgres增量更新sql等功能)
    undefined: grpc.SupportPackageIsVersion6 和 undefined: grpc.ClientConnInterface 解决办法
    micrometer埋点(Spring boot 2.X metrics)
  • 原文地址:https://www.cnblogs.com/lara0520/p/8353115.html
Copyright © 2020-2023  润新知