python中字典(Dictionary)用法实例详解
Jun 06, 2016 am 11:17 AM本文实例讲述了python中字典(Dictionary)用法。分享给大家供大家参考。具体分析如下:
字典(Dictionary)是一种映射结构的数据类型,由无序的“键-值对”组成。字典的键必须是不可改变的类型,如:字符串,数字,tuple;值可以为任何python数据类型。
1、新建字典
1 2 3 |
|
2、增加字典元素:两种方法
1 2 3 4 5 6 7 8 |
|
3、删除字典
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
4、字典的方法
1)get(key,default=None)
返回键值key对应的值;如果key没有在字典里,则返回default参数的值,默认为None
1 2 3 4 5 6 7 8 9 10 |
|
2)clear 清空字典
3)has_key(key) 如果key出现在dict里则返回True;否则返回False
1 2 3 4 5 6 |
|
4)items 返回dict的(键,值)tuple对的一个列表
1 2 3 4 |
|
5)keys 返回dict的键列表
6)values 返回dict的值列表
1 2 3 4 5 6 |
|
7)setdefault(key,default=None)
如果dict中有key,则返回key值,如果没有找到key,则在dict中加上该key,值由default参数给出,默认None
8)update(dict2)
把dict2的元素加入到dict中去,键字重复时会覆盖dict中的键值
1 2 3 4 5 6 7 |
|
9)popitem 删除任意键-值对,并返回该键-值对,如字典为空,则产生异常
1 2 3 4 5 6 7 8 9 10 |
|
10)pop(key,[d]) 删除指定键字的键-值对,并返回该键对应的值
1 2 3 4 5 6 |
|
11)copy 返回字典的一个浅拷贝
希望本文所述对大家的Python程序设计有所帮助。

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the advantages and disadvantages of templating?

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers

For only $250, Hugging Face's technical director teaches you how to fine-tune Llama 3 step by step

Share several .NET open source AI and LLM related project frameworks

A complete guide to golang function debugging and analysis
