Peer-reviewed code snippets that anyone can edit
A wiki for useful code snippets
Lua for Pythoners - Dictionary
-- Using Lua standard libraries and Penlight (http://luaforge.net/frs/?group_id=450)
-- Dictionary catalog: http://www.java2s.com/Code/Python/Dictionary/CatalogDictionary.htm
package.path=package.path..';./?/init.lua'
require 'pl'
stringx.import()
function Map:items()
    return List (tablex.pairmap (function (k,v) return List {k,v} end, self))
end
function Map:setdefault(key, defaultval)
    return self[key] or self:set(key,defaultval) or defaultval
end
 
print("=== Dictionary")
print("== Dictionary Assignment")
print ("= Dictionary assignment")
x = {}
y = x
x['key'] = 'value'
print (pretty.write(y))
 
x = {}
print (pretty.write(y))
 
x = {}
y = x
y['key'] = 'value'
print (pretty.write(y))
 
print (tablex.clear(x))
print (pretty.write(y))
 
print("= Change dictionary entry")
d2 = {spam=2, ham=1, eggs=3}    -- make a dictionary
print (pretty.write(d2)) -- order is scrambled
 
d2['ham'] = {'grill', 'bake', 'fry'}      -- change entry
print (pretty.write(d2))
 
print ("=Add new entry to a dictionary")
d2 = {spam=2, ham=1, eggs=3}    -- make a dictionary
print (pretty.write(d2))                   -- order is scrambled
 
d2['ham'] = {'grill', 'bake', 'fry'}      -- change entry
 
d2['eggs'] = nil                            -- delete entry
d2['brunch'] = 'Bacon'                  -- add new entry
print (pretty.write (d2))
 
print ("== Dictionary get")
print ("= Dictionary get value")
d = {}
--Not so with get:
print (d['name'])
--You may supply your own "default" value, which is then used instead of nil:
print (d['name'] or 'N/A')
-- If the key is there, get works like ordinary dictionary lookup:
d['name'] = 'Eric'
print (d['name'])
 
print ("== Dictionary Loop")
print ("= Looping through dictionaries")
knights = {['Key 1']='value 1', ['key 2']='value 2'}
for k, v in pairs (knights) do
     print (k, v)
end
 
print ("= for each loop with dictionary")
D = {a=1, b=2, c=3}
for key,_ in pairs(D) do
     print (key, D[key])
end
 
print ("== Dictionary update")
print ("= Update a dictionary")
d2 = Map {spam=2, ham=1, eggs=3}    -- make a dictionary
print (d2)                                      -- order is scrambled
d3 = {toast=4, muffin=5}
d2:update(d3)
print (d2)
 
print ("== Dictionary Clear")
print ("= Dictionary: clear method removes all items from the dictionary")
d = {}
d['name'] = 'Gumby'
d['age'] = 42
print (pretty.write (d))
 
returned_value = tablex.clear(d)
print (pretty.write(d))
print (returned_value)
 
print ("== Dictionary has Key")
print ("= Key membership test in a dictionary")
d2 = {spam=2, ham=1, eggs=3}    -- make a dictionary
print (pretty.write(d2))         -- order is scrambled
print (d2['ham'] ~= nil)
 
print ("= Dictionary has_key method")
d = {}
print (d['name'] ~= nil)
 
d['name'] = 'Eric'
print (d['name'] ~= nil)
 
print ("= Reference dictionary in print function")
-- print "%(n)d %(x)s" % {"n":1, "x":"spam"}
-- couldn't find any solution for this!
 
print ("== Dictionary values")
print ("= Dictionary: The keys, values, and items Functions")
params = Map {server="mpilgrim", database="master", uid="sa", pwd="secret"} 
print (params:keys())
print (params:values())
print (params:items())
 
print ("== Dictionary Copy")
print ("= Copy a dictionary")
L = List {1,2,3}
D = {a=1, b=2}
 
A = L:slice(nil,nil)              -- instead of: A = L (or list(L))
B = tablex.copy (D)          -- instead of: B = D
 
A[2] = 'Ni'
B['c'] = 'spam'
 
print (pretty.write(L), pretty.write(D))
print (pretty.write(A), pretty.write(B))
 
print("= Dictionary deep copy")
d = Map {}
d['names'] = List {'Alfred', 'Bertrand'}
c = Map(tablex.copy (d))
dc = tablex.deepcopy (d)
d['names']:append('Clive')
print (c)
print (dc)
 
print("== Dictionary Declaration")
print ("= Dictionaries are indexed by keys, which can be any immutable type")
-- In Lua you can use tables (mutable types in general) as keys, while you can't in Python
t = {'john', 'matt'}
tel = {jack=4098, sape=4139, t=4223, [{1,2,3}]='something'}
print (tel[t]) -- Lua has no hash function, so key lookup is based on pointers (__eq is ignored)
 
print ("== Dictionary Key")
print ("= Sorting Keys: for Loops")
D = Map {a=1, b=2, c=3}
 
Ks = D:keys()                         -- Unordered keys list
print (Ks)
Ks:sort()                             -- Sorted keys list
print (Ks)
 
for key in Ks:iter() do               -- Iterate though sorted keys
    print (key, '=>', D[key])
end
 
for key in seq.sort(seq.keys(D)) do
    print (key, '=>', D[key])
end
 
print("== Dictionary setdefault")
print ("= Dictionary setdefault ")
d = Map {}
d:setdefault('name', 'N/A')
print (d)
 
d['name'] = 'Gumby'
d:setdefault('name', 'N/A')
print (d)
 
d = Map {}
print (d:setdefault('name'))
print (d) -- notice that for Lua a nil value means unexisting entry in the table