{k: v for k, v in d.iteritems() if v['your key'] > 90}
集合解析
针对集合,我们也有集合解析,形式上与字典解析一致。例如,我们要筛选出集合中所有可以被3整除的数。
1
2
3
4
# 筛选出集合中所有可以被3整除的数
s = {2, -2, 3, 2, 5, 1, -3, 3, 0, 3}
{x for x in s if x % 3 == 0}
iteritems
iteritemsDescription
Returns an iterator over the dictionary’s (key, value) pairs.
Syntax
dict. iteritems()
Return Value
iterator
Remarks
See also dict.items(). Using iteritems() while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.
Example
1
2
3
4
5
6
7
8
9
10
>>> d = {'a': 1, 'b': 2}
>>> di = d.iteritems()
>>> di.next()
('a', 1)
>>> di.next()
('b', 2)
>>> di.next()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
StopIteration
Example 2
1
2
3
4
5
6
7
8
9
>>> d = {'a': 1, 'b': 2}
>>> di = d.iteritems()
>>> di.next()
('a', 1)
>>> d['x'] = 'foobar'# adding a new key:value pair during iterarion;
>>> di.next() # that raises an error later on
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
RuntimeError: dictionary changed size during iteration