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

Content deleted Content added
m Mathematica and Wolfram Language: <source lang="mathematica">
Python: <source lang=Pycon> dictionary comprehensions in Python 2.7 and 3.x
Line 1,062:
</source>
 
To access an entry in Python simply use the array indexing operator. For example, the
<source expressionlang=Pycon>
>>> <code>phonebook['Sally Smart']</code> would return <code>
'555-9999'</code>.
</source>
 
An example loop [[iterator#Python|iterating]] through all the keys of the dictionary:
 
<source lang=PythonPycon>
>>> for key in phonebook:
... print key, phonebook[key]
Sally Smart 555-9999
J. Random Hacker 553-1337
John Doe 555-1212
</source>
 
Iterating through (key, value) tuples:
 
<source lang=PythonPycon>
>>> for key, value in phonebook.itemsiteritems():
... print key, value
Sally Smart 555-9999
</source>
J. Random Hacker 553-1337
 
John Doe 555-1212
Dictionaries can also be constructed with the <code>dict</code> builtin, which is most commonly found inside list comprehensions and generator expressions, and it takes a key-value list:
 
<source lang=Python>
dict((key, value) for key, value in phonebook.items() if 'J' in key)
</source>
 
Dictionary keys can be individually deleted using the del statement. The corresponding value can be returned before the key-value pair are deleted using the pop method of dict types:
 
<source lang=PythonPycon>
>>> del phonebook['John Doe']
>>> val = phonebook.pop('Sally Smart')
assert>>> phonebook.keys() == ['J. Random Hacker'] # Only one key left
['J. Random Hacker']
</source>
 
Python 2.7 and 3.0x also supports dictionary comprehensions, a compact syntax for generating a dictionary from any iterator:
<source lang=PythonPycon>
>>> square_dict={i:i*i for i in range(5)}
assert>>> square_dict ==
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
dict((>>> {key,: value) for key, value in phonebook.itemsiteritems() if 'J' in key)}
{'J. Random Hacker': '553-1337', 'John Doe': '555-1212'}
</source>