Associative array/Creation: Difference between revisions

Merge two entrys of Python
(Remove double entry for Ruby)
(Merge two entrys of Python)
Line 229:
 
Numerous methods exist for the mapping type http://docs.python.org/lib/typesmapping.html
 
# empty dictionary
d = {}
d['spam'] = 1
d['eggs'] = 2
 
# dictionaries with two keys
d1 = {'spam': 1, 'eggs': 2}
d2 = dict(spam=1, eggs=2)
 
# dictionaries from tuple list
d1 = dict([('spam', 1), ('eggs', 2)])
d2 = dict(zip(['spam', 'eggs'], [1, 2]))
 
# iterating over keys
for key in d:
print key, d[key]
 
# iterating over (key, value) pairs
for key, value in d.iteritems():
print key, value
 
Create a generic mapping function that applys a callback to elements in a list:
 
==[[Ruby]]==
Line 327 ⟶ 350:
@hash->{'key1', 'three'} = ('val1', -238.83);
 
==[[Python]]==
[[Category:Python]]
In Python, hashes are called dictionaries.
 
# empty dictionary
d = {}
d['spam'] = 1
d['eggs'] = 2
 
# dictionaries with two keys
d1 = {'spam': 1, 'eggs': 2}
d2 = dict(spam=1, eggs=2)
 
# dictionaries from tuple list
d1 = dict([('spam', 1), ('eggs', 2)])
d2 = dict(zip(['spam', 'eggs'], [1, 2]))
 
# iterating over keys
for key in d:
print key, d[key]
 
# iterating over (key, value) pairs
for key, value in d.iteritems():
print key, value
 
Create a generic mapping function that applys a callback to elements in a list:
 
==[[Smalltalk]]==