Python教程

python 字典超详细小结

本文主要是介绍python 字典超详细小结,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

字典

   python中,字典还是一些列的键-值对。每个键都与一个值相关联。键是不可变类型也不能重复,值可以是任意类型,可以将任何python对象用作字典中的值。

        键值之间用冒号隔开,键值对之间用逗号隔开。在字典中你存储多少个键值对都可以

         sample:

        

dict_sample = {"name": "甲壳虫~~~", "age": "18"}

 

创建字典

赋值创建,函数创建

  •  创建空字典
     person1_info = {}
  • 创建简单单值字典
    person2_info = {"name": "甲壳虫", "age": "18"}

     

  • 创建 多个键值对
    person2_info = {"name": "甲壳虫", 
                             "age": 18,
                             "sex": "男",
                             "garde": "七年级",
                             "addr":["中国","江苏省", "南京市"],
                             ""friends": {"name1": "Jack", "name2": "Merry"}
    
                           }      
  • dict函数
    print(dict([()]))
    """
     |  dict() -> new empty dictionary
     |  dict(mapping) -> new dictionary initialized from a mapping object's
     |      (key, value) pairs
     |  dict(iterable) -> new dictionary initialized as if via:
     |      d = {}
     |      for k, v in iterable:
     |          d[k] = v
     |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
     |      in the keyword argument list.  For example:  dict(one=1, two=2)
     下面还有很多。。。仅仅截取这些
    """

     

       
  • 创建空字典
    print(dict()) #{}
  • 创建多个键值对
    #(iterable,可迭代对象)
    cattle = [("name", "甲壳虫~~~"), ("age", 18), ("sex", "男")]
    print(dict(cattle))#{'name': '甲壳虫~~~', 'age': 18, 'sex': '男'}
    peach = [["name", "桃子"], ["age", 16], ["sex", "女"]]
    print(dict(peach))#{'name': '桃子', 'age': 16, 'sex': '女'}

     

  • 指定关键字创建字典
    1 baby = dict(name="Little Baby", sex="男")
    2 print(baby, '~~~', type(baby))#{'name': 'Little Baby', 'sex': '男'} ~~~ <class 'dict'>

     

  • zip()
    zip_data = zip(("name", "age", "sex"), ("peach", 16, "girl"))
    print(dict(zip_data))#{'name': 'peach', 'age': 16, 'sex': 'girl'}

     

 使用字典

字典是键值对形式存在字典中。键和值是一种映射关系。

获取字典中的,值,键和值;

  • 通过key查询value,如果键不存在怎抛出异常
    dic = {"name": "甲壳虫", "age": 18}
    print(dic['name'])#甲壳虫
    print(dic["sex"])#KeyError: 'sex'

     

  • 添加键值对
    dic = {"name": "甲壳虫", "age": 18}
    dic['sex'] = '男'
    print(dic)#{'name': '甲壳虫', 'age': 18, 'sex': '男'}

     

  • 删除键值对
    dic = {"name": "甲壳虫", "age": 18}
    dic['sex'] = '男'
    del dic["age"]
    print(dic)#{'name': '甲壳虫', 'sex': '男'}

     

  • 修改键值对
    dic = {"name": "甲壳虫", "age": 18}
    dic['sex'] = '女'
    print(dic)#{'name': '甲壳虫', 'age': 18, 'sex': '女'}

     

  • 判断字典中是否有对应的键
    dic = {"name": "甲壳虫", "age": 18}
    key_in = "name" in dic
    print(key_in)#True
    key_not_in = 'sex' in dic
    print(key_not_in)#False

     

  • 判断字典中是否有对应的值
    dic = {"name": "甲壳虫", "age": 18}
    value_in = "甲壳虫" in dic["name"]
    print(value_in)

     其实还是根据键,获取到对应的值,然后在去测试是否在字典中(in , not in )

  • 字典的方法-->字典也是一个类

  • clear()方法
    dic = {"name": "甲壳虫", "age": 18}
    """ D.clear() -> None.  Remove all items from D. """
    a = dic.clear()
    print(a)#None

     

  • get()方法
    dic = {"name": "甲壳虫", "age": 18}
    """ Return the value for key if key is in the dictionary, else default.None"""
    print(dic.get("name", "这个默认值是否返回"))#甲壳虫
    
    print(dic.get("sex", "键不在字典中,这里返回了此处设置的默认值"))#键不在字典中,这里返回了此处设置的默认值

     

  • update()
    dic = {"name": "甲壳虫", "age": 18}
    """ D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]"""
    dic.update({"name": "peach"})#键存在 更新键所对应的值
    print(dic)#{'name': 'peach', 'age': 18}
    dic.update({"friend": "peach"})#不键存在 ,添加新的键值对
    print(dic)#{'name': 'peach', 'age': 18, 'friend': 'peach'}

     

  • setdefault
     1 dic = {"name": "甲壳虫", "age": 18}
     2 """ Insert key with a value of default if key is not in the dictionary.
     3     Return the value for key if key is in the dictionary, else default.
     4 None"""
     5 """如果键不在字典中,向字典中添加对应的键值对;并返回默认值
     6    如果键在字典中,直接返回默认的值
     7 """
     8 print(dic.setdefault("age", None))#键在字典中,返回键所对应的值
     9 print(dic)#{'name': '甲壳虫', 'age': 18}
    10 print(dic.setdefault("friend", "键不在字典中"))#键不在字典中,返回设置的值:键不在字典中
    11 print(dic)#字典中添加了新的键值对{'name': '甲壳虫', 'age': 18, 'friend': '键不在字典中'}

     

  • pop()
    dic = {"name": "甲壳虫", "age": 18}
    """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, default is returned if given, otherwise KeyError is raised
    None"""
    
    print(dic.pop("name"))#甲壳虫
    print(dic)#{'age': 18}

     

  • popeitem()
    dic = {"name": "甲壳虫", "age": 18}
    """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, default is returned if given, otherwise KeyError is raised
    None"""
    
    print(dic.popitem())#('age', 18)
    print(dic)#{'name': '甲壳虫'}

     

  • fromkeys()
    """fromkeys(iterable, value=None, /) method of builtins.type instance
        Create a new dictionary with keys from iterable and values set to value.
    None"""
    lst = ["name-1", "name-2"]
    dict_tester = dict(dict.fromkeys(lst))
    print(dict_tester)#{'name-1': None, 'name-2': None}
    tup = ("name-1", "name-2")
    print(dict.fromkeys(tup))#{'name-1': None, 'name-2': None}
    print(dict.fromkeys(["name-1", "name-2", "姓名"]))#{'name-1': None, 'name-2': None, '姓名': None}

     

  • keys(),values(),item()

 

这篇关于python 字典超详细小结的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!