Python 中的字典数据类型
Python 的字典属于哈希表类型。它们像 Perl 中的关联数组或哈希表一样运作,并由键值对组成。字典键可以是几乎任何 Python 类型,但通常是数字或字符串。而值可以是任何任意的 Python 对象。
示例
字典用大括号 ({ }) 括起来,可以使用方括号 ([]) 分配和访问值。例如 −
#!/usr/bin/python
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values输出
产生以下结果 −
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']字典元素之间没有顺序概念。错误地认为元素“无章可循”,它们只是无序的。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP