Content deleted Content added
m →Rust: add syntax highlighting |
m →Python: Blackened |
||
Line 1,495:
In [[Python (programming language)|Python]], associative arrays are called "[[Python syntax and semantics#Collection types|dictionaries]]". Dictionary literals are delimited by curly braces:
<syntaxhighlight lang=
phonebook = {
}
</syntaxhighlight>
To access an entry in Python simply use the array indexing operator:
<syntaxhighlight lang=
>>> phonebook[
'555-9999'
</syntaxhighlight>
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
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
>>> {key: value for key, value in phonebook.items() if
{'J. Random Hacker': '553-1337', 'John Doe': '555-1212'}
</syntaxhighlight>
Line 1,550:
Strictly speaking, a dictionary is a super-set of an associative array, since neither the keys or values are limited to a single datatype. One could think of a dictionary as an "associative list" using the nomenclature of Python. For example, the following is also legitimate:
<syntaxhighlight lang=
phonebook = {
14:
}
</syntaxhighlight>
|