字典

   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}
    print(dict.fromkeys(["name-1", "name-2"], "姓名"))#{'name-1': '姓名', 'name-2': '姓名'}
     

     

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


     1 # -*- ecoding: utf-8 -*-
     2 # @ModuleName: exercise_demo
     3 # @Function: 
     4 # @Author: 甲壳虫~~~
     5 # @Time: 2021/8/29 8:57
     6 #@blog:https://www.cnblogs.com/liveforlearn
     7 
     8 
     9 cattle = {"name": '甲壳虫~~~', "age": 18, "sex": ""}
    10 
    11 print('\n', cattle.keys(), type(cattle.keys()))#dict_keys(['name', 'age', 'sex']) <class 'dict_keys'>
    12 """ D.keys() -> a set-like object providing a view on D's keys """
    13 for key in cattle.keys():
    14     print(key, end=' ')# name age sex
    15 
    16 print('\n', cattle.values(), type(cattle.values()))#dict_values(['甲壳虫~~~', 18, '男']) <class 'dict_values'>
    17 """ D.values() -> an object providing a view on D's values """
    18 for value in cattle.values():
    19     print(value, end=' ')#甲壳虫~~~ 18 男
    20 
    21 print('\n', cattle.items(), type(cattle.items()))#dict_items([('name', '甲壳虫~~~'), ('age', 18), ('sex', '男')]) <class 'dict_items'>
    22 """ D.items() -> a set-like object providing a view on D's items """
    23 for k, v in cattle.items():
    24     print(k, v, end=' ')#name 甲壳虫~~~ age 18 sex 男



练一练

统计可迭代对象中的元素

  get-->

 1 # -*- ecoding: utf-8 -*-
 2 # @ModuleName: exercise_demo
 3 # @Function:
 4 # @Author: 甲壳虫~~~
 5 # @Time: 2021/8/29 8:57
 6 #@blog:https://www.cnblogs.com/liveforlearn
 7 show = ['刘备', '关羽', '张飞', '曹操', '曹操', '刘备', '曹操', '刘备', '关羽', '曹操']
 8 "简单模拟;统计三国中人名出现的次数"
 9 show_times = {}
10 for i in show:
11     show_times[i] = show_times.get(i, 0) + 1
12 print(show_times)#{'刘备': 3, '关羽': 2, '张飞': 1, '曹操': 4}

setdefault-->

# -*- ecoding: utf-8 -*-
# @ModuleName: exercise_demo
# @Function:
# @Author: 甲壳虫~~~
# @Time: 2021/8/29 8:57
#@blog:https://www.cnblogs.com/liveforlearn
show = ['刘备', '关羽', '张飞', '曹操', '曹操', '刘备', '曹操', '刘备', '关羽', '曹操']
"简单模拟;统计三国中人名出现的次数"
show_times = {}
for i in show:
    show_times.setdefault(i, 0)
    show_times[i] += 1

print(show_times)#{'刘备': 3, '关羽': 2, '张飞': 1, '曹操': 4}

defaultdict-->

# -*- ecoding: utf-8 -*-
# @ModuleName: exercise_demo
# @Function:
# @Author: 甲壳虫~~~
# @Time: 2021/8/29 8:57
# @blog:https://www.cnblogs.com/liveforlearn
show = ['刘备', '关羽', '张飞', '曹操', '曹操', '刘备', '曹操', '刘备', '关羽', '曹操']
"简单模拟;统计三国中人名出现的次数"
from collections import defaultdict
#用于构建对象,接受一个函数(可调用)对象作为参数。参数返回的类型是什么,key对应的value就是什么类型
"""
   defaultdict(default_factory[, ...]) --> dict with default factory

   The default factory is called without arguments to produce
   a new value when a key is not present, in __getitem__ only.
   A defaultdict compares equal to a dict with the same items.
   All remaining arguments are treated the same as if they were
   passed to the dict constructor, including keyword arguments.
   """
show_time = defaultdict(list)
print(show_time)#defaultdict(<class 'list'>, {})
for (key, value) in show:
    show_time[key].append(value)

print(show_time)#defaultdict(<class 'list'>, {'刘': ['备', '备', '备'], '关': ['羽', '羽'], '张': ['飞'], '曹': ['操', '操', '操', '操']})

 

 试一试

# -*- ecoding: utf-8 -*-
# @ModuleName: get_demo
# @Function: 
# @Author: 甲壳虫~~~
# @Time: 2021/8/27 6:36
#@blog:https://www.cnblogs.com/liveforlearn


data = [("甲壳虫", 1), ("甲壳虫", 1), ("甲壳虫", 3),
        ("peach", 1), ("peach", 1), ("peach", 1),
        ("age", 11),  ("age", 12),  ("age", 13)
        ]
result = {}
# for (key, value) in data:
#     if key not in result:
#         result[key] = []
#     result[key].append(value)
#
# print(result)

for (key, value) in data:
    result.setdefault(key, []).append(value)
print(result)#{'甲壳虫': [1, 1, 3], 'peach': [1, 1, 1], 'age': [11, 12, 13]}
from collections import defaultdict
#用于构建对象,接受一个函数(可调用)对象作为参数。参数返回的类型是什么,key对应的value就是什么类型
"""
   defaultdict(default_factory[, ...]) --> dict with default factory

   The default factory is called without arguments to produce
   a new value when a key is not present, in __getitem__ only.
   A defaultdict compares equal to a dict with the same items.
   All remaining arguments are treated the same as if they were
   passed to the dict constructor, including keyword arguments.
   """
result = defaultdict(list)
print(result)#defaultdict(<class 'list'>, {})
for (key, value) in data:
    result[key].append(value)

print(result)#defaultdict(<class 'list'>, {'甲壳虫': [1, 1, 3], 'peach': [1, 1, 1], 'age': [11, 12, 13]})

for (key, value) in data:
    if key not in result:
        result[key] = result.get(key, [])
    result[key].append(value)

print(result)#defaultdict(<class 'list'>, {'甲壳虫': [1, 1, 3, 1, 1, 3], 'peach': [1, 1, 1, 1, 1, 1], 'age': [11, 12, 13, 11, 12, 13]})