python字典学习
2017-04-25 10:31
197 查看
字典用来储存(键, 值)对,这和Java中的Map差不多。你可以这样使用它:
想要知道字典的其他特性,请查阅文档。
循环Loops:在字典中,用键来迭代更加容易。
如果你想要访问键和对应的值,那就使用iteritems方法:
字典推导Dictionary comprehensions:和列表推导类似,但是允许你方便地构建字典。
d = {'cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some data print d['cat'] # Get an entry from a dictionary; prints "cute" print 'cat' in d # Check if a dictionary has a given key; prints "True" d['fish'] = 'wet' # Set an entry in a dictionary print d['fish'] # Prints "wet" # print d['monkey'] # KeyError: 'monkey' not a key of d print d.get('monkey', 'N/A') # Get an element with a default; prints "N/A" print d.get('fish', 'N/A') # Get an element with a default; prints "wet" del d['fish'] # Remove an element from a dictionary print d.get('fish', 'N/A') # "fish" is no longer a key; prints "N/A"
想要知道字典的其他特性,请查阅文档。
循环Loops:在字典中,用键来迭代更加容易。
d = {'person': 2, 'cat': 4, 'spider': 8} for animal in d: legs = d[animal] print 'A %s has %d legs' % (animal, legs) Prints "A person has 2 legs", "A spider has 8 legs", "A cat has 4 legs"
如果你想要访问键和对应的值,那就使用iteritems方法:
d = {'person': 2, 'cat': 4, 'spider': 8} for animal, legs in d.iteritems(): print 'A %s has %d legs' % (animal, legs) # Prints "A person has 2 legs", "A spider has 8 legs", "A cat has 4 legs"
字典推导Dictionary comprehensions:和列表推导类似,但是允许你方便地构建字典。
nums = [0, 1, 2, 3, 4] even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0} print even_num_to_square # Prints "{0: 0, 2: 4, 4: 16}"
相关文章推荐
- python学习手册笔记--第8章--列表与字典
- python学习笔记——字典
- Python基础教程学习笔记----第四章 字典
- python字典学习
- Python学习笔记:列表,元组和字典
- python学习(1)-字典 (Dictionary)
- python学习五 列表(list)、字典(dict)、字符串(string)
- Debian Linux下的Python学习——列表,元组和字典之元组
- Debian Linux下的Python学习——列表,元组和字典之列表
- Python 学习笔记 -- 变量、元组、列表、字典和集合
- [python学习笔记]字典,当索引不好用时
- python学习总结六(python字典)
- Dive Into Python 学习记录1-函数/模块导入/字典/列表/元组/字符串分割、连接、格式化/映射list/
- python学习笔记4-核心类型-字典
- 深入学习Python内置数据类型之——字典(Dictionary)
- python 学习笔记之字典
- python学习笔记——字典
- python学习字典
- python学习笔记:字典