>>> languages = {
'Spain': 'Spanish',
'Great Britain': 'English',
'Italy': 'Italian',
'Mexico': 'Spanish',
'France': 'French',
'USA': 'English',
}
>>> print languages['Mexico']
'Spanish'
>>> capitals = {
'Germany': 'Berlin',
'France': 'Paris',
'Brazil': 'Brasilia',
'Malaysia': 'Kuala Lumpur',
}
>>> print capitals['Brazil']
'Brasilia'
>>> capitals['Brazil'] = 'Brazil'
>>> print capitals['Brazil']
'Brazil'
>>> capitals['Sweden'] = 'Stockholm'
>>> print capitals['Sweden']
'Stockholm'
>>> del capitals['Malaysia']
>>> print capitals['Malaysia']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'capitals' is not defined
>>> capitals = {
'Germany': 'Berlin',
'France': 'Paris',
'Brazil': 'Rio de Janeiro',
'Sweden': 'Stockholm',
}
>>> capitals.get('Assyria')
None
>>> capitals.get('Assyria', "I don't know")
"I don't know"
>>> capitals.has_key('Sweden')
True
>>> capitals.keys()
['Brazil', 'France', 'Germany', 'Sweden']
>>> capitals.values()
['Berlin', 'Paris', 'Brazil', 'Stockholm']
>>> numbers = {
"One": "I",
"Two": "II",
}
>>> numbers.items()
[('One', 'I'), ('Two', 'II')]
>>> numbers.update({"Three": "III", "Four": "IV"})
{'Four': 'IV', 'Three': 'III', 'Two': 'II', 'One': 'I'}
>>> numbers.pop('Four')
'IV'
>>> numbers
{'Three': 'III', 'Two': 'II', 'One': 'I'}
>>> numbers.popitem()
{'Three': 'III'}
>>> numbers.popitem()
{'One': 'I'}
>>> dict(france="Paris", italy="Rome")
{'italy': 'Rome', 'france': 'Paris'}
>>> dict([('One', 'I'), ('Two', 'I')])
{'Two': 'I', 'One': 'I'}
for [променлива] in [колекция]
[блок]
break
излиза от цикълаcontinue
прекъсва текущата итерация и продължава изпълнението на цикъла от следващия елементrange(x, y)
връща списък от числата в интервала [x, y)
>>> range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(0, 10, 2)
[0, 2, 4, 6, 8]
>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
for n in range(0, 20):
if n % 2: continue
print n
if n > 10: break
Произвежда следния резултат:
0
2
4
6
8
10
12
roman = {1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V'}
numbers = [2, 3, 5]
for n in numbers:
print n, "is", roman[n]
Получава:
2 is II in Roman numbers
3 is II in Roman numbers
5 is V in Roman numbers