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,
<source >>> '555-9999' </source>▼
An example loop [[iterator#Python|iterating]] through all the keys of the dictionary:
<source lang=
>>> for key in phonebook:
Sally Smart 555-9999
J. Random Hacker 553-1337
John Doe 555-1212
</source>
Iterating through (key, value) tuples:
<source lang=
>>> for key, value in phonebook.
Sally Smart 555-9999
▲</source>
J. Random Hacker 553-1337
John Doe 555-1212
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=
>>> del phonebook['John Doe']
>>> val = phonebook.pop('Sally Smart')
['J. Random Hacker']
</source>
Python 2.7 and 3.
<source lang=
>>> square_dict={i:i*i for i in range(5)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16} {'J. Random Hacker': '553-1337', 'John Doe': '555-1212'}
</source>
|