louyaoluan 发表于 2018-8-12 08:12:41

python dict()方法学习笔记

  学习PYTHON 的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 = v
  |dict(**kwargs) -> new dictionary initialized with the name=value pairs
  |      in the keyword argument list.For example:dict(one=1, two=2)
  dict()方法四种样式:
  dict():   原型
  dict(maping):    映射
  dict(iterable):   迭代
  dict(**kwargs):解包,函数调用
  原型:
  dict():用于建立空的字典
  映射: 迭代样式:
  在我看来,没什么区别(个人看法,欢迎交流)
  iterable/mapping-->只能是一种可迭代数据结构,且只有是一个,不可能为多个,可以是一个元组、列表,其元素格式为(key, value)或是(要以这种样式,是最重要的,也是我认为map,iterable,这两种方式是一样的)。
  如:dict('a','b')会出现错误:
  TypeError: dict expected at most 1 arguments, got 2(出现多个参数)
  如:dict((['a', 'b'],('c', 'd'))),元组的元素可是列表,也可是元组,但要以(key, value)样式出现。
  解包,函数调用样式:
  1、**kwargs 可以字典解包,而kwargs是一个字典;
  d1 = {'a': 'b', 'c': 'd'}
  d2 = dict(**d1)
  d2 -->   {'a': 'b', 'c': 'd'}
  2、函数调用:将dict()做为一个函数,通过关键字方式来进行调用,类似这样的方式。
  dict(a=1, b=2)-->   {'a':1, 'b':2}可以得到一个以参数名为key, 参数值为value的字典。
页: [1]
查看完整版本: python dict()方法学习笔记