Comparison of programming languages (associative array): Difference between revisions

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=Python"python">
phonebook = {
'"Sally Smart'": '"555-9999'",
'"John Doe'": '"555-1212'",
'"J. Random Hacker'": '"553-1337'",
}
</syntaxhighlight>
 
To access an entry in Python simply use the array indexing operator:
<syntaxhighlight lang=Pycon"pycon">
>>> phonebook['"Sally Smart'"]
'555-9999'
</syntaxhighlight>
Line 1,511:
Loop [[iterator#Python|iterating]] through all the keys of the dictionary:
 
<syntaxhighlight lang=Pycon"pycon">
>>> for key in phonebook:
... print(key, phonebook[key])
Line 1,521:
Iterating through (key, value) tuples:
 
<syntaxhighlight lang=Pycon"pycon">
>>> 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=Pycon"pycon">
>>> 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=Pycon"pycon">
>>> 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'" in key}
{'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=Python"python">
phonebook = {
'"Sally Smart'": '"555-9999'",
'"John Doe'": None,
'"J. Random Hacker'": -3.32,
14: '"555-3322'",
}
</syntaxhighlight>