Python字典高级使用方法汇总

本文汇总了Python字典的一些高级使用方法,包括通过不同方式创建字典、设置默认值、利用`defaultdict`和`get`方法以及多种遍历方式。详细介绍了字典推导式、`defaultdict`的使用以及动态遍历字典的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python字典高级使用方法汇总

字典(dictionary)是python中的一种非常灵活和强大的数据结构,可以完成很多操作。本文总结了一些除了基本的初始化、赋值、取值之外的常用的字典使用方法。

字典基础参考:
【1】:http://www.w3cschool.cc/python/python-dictionary.html
【2】:http://www.111cn.net/phper/python/56355.htm
【3】:http://skyfen.iteye.com/blog/567571
【4】:http://www.cnblogs.com/rubylouvre/archive/2011/06/19/2084739.html

使用dict创建字典的n种方法

除了我们比较常用的d = {'a':1, 'b':2}来初始化字典外,还可以使用dict()来初始化,这种方法更为灵活。以下介绍了用dict来初始化字典的几种方法。

In [2]: dict?
Type:        type
String form: <type 'dict'>
Namespace:   Python builtin
Docstring:
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)

参数赋值

In [6]: d = dict(a=1,b=2)
In [7]: d
Out[7]: {
  
  'a': 1, 'b': 2}

用可迭代对象为参数,且每一个迭代对象为(k, v)

In [8]: l1 = ['a', 'b', 'c']
In [9]: l2 = [1, 2, 3]
In [11]: zip(l1,l2)
Out[11]: [('a', 1), ('b', 2), ('c', 3)]
In [12]: d = dict(zip(l1,l2))
In [13]: d
Out[13]: {
  
  'a': 1, 'b': 2, 'c': 3}

字典推导式(dictionary comprehension)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值