Content deleted Content added
m →Python: Blackened |
→Python: changing "pycon" to "python" in syntaxhighlight tag (using wikEd) |
||
Line 1,504:
To access an entry in Python simply use the array indexing operator:
<syntaxhighlight lang="
>>> phonebook["Sally Smart"]
'555-9999'
Line 1,511:
Loop [[iterator#Python|iterating]] through all the keys of the dictionary:
<syntaxhighlight lang="
>>> for key in phonebook:
... print(key, phonebook[key])
Line 1,521:
Iterating through (key, value) tuples:
<syntaxhighlight lang="
>>> for key, value in phonebook.items():
... print(key, value)
Line 1,531:
Dictionary keys can be individually deleted using the <code>del</code> statement. The corresponding value can be returned before the key-value pair is deleted using the "pop" method of "dict" type:
<syntaxhighlight lang="
>>> del phonebook['John Doe']
>>> val = phonebook.pop('Sally Smart')
Line 1,540:
Python 2.7 and 3.x also support dictionary [[list comprehension]], a compact syntax for generating a dictionary from any iterator:
<syntaxhighlight lang="
>>> square_dict = {i: i*i for i in range(5)}
>>> square_dict
|