Erlang Central

# Retrieving Element From Hash

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

## Problem

You need to retrieve an entry from a Hash.

## Solution

Use the dict:fetch/2 to retrieve an element from an existing Dictionary.

```1> Dict = dict:new().
{dict,0,
16,
16,
8,
80,
48,
{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
{{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]}}}
2> Dict2 = dict:append(1, "foo", Dict).
{dict,1,
16,
16,
8,
80,
48,
{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
{{[],[],[],[],[],[],[],[],[],[],[],[[1,"foo"]],[],[],[],[]}}}
3> dict:fetch(1, Dict2).
["foo"]
```

Use the ets:lookup/2 function to find an element in an existing ETS table.

```1> ets:new('Cookbook Test',[public,named_table]).
'Cookbook Test'
2> ets:insert('Cookbook Test',{dog,1,{"Jake",white,20,12}}).
true
3> ets:insert('Cookbook Test',{dog,2,{"Dylan",black,30,8}}).
true
4> ets:insert('Cookbook Test',{dog,3,{"Macy",blue,10,1}}).
true
5> ets:insert('Cookbook Test',{cat,1,{"Kitty",white,10,4}}).
true
6> ets:lookup('Cookbook Test',dog).
[{dog,3,{"Macy",blue,10,1}}]
7> ets:lookup('Cookbook Test',cat).
[{cat,1,{"Kitty",white,10,4}}]
8>
```

## Discussion

Note that ets:insert is destructive, so if you pass the same key a second time, the new element will overwrite the old one associated to the key. An exception to this rule is that if the ets table is created as a duplicate bag, duplicates of the same key/value pairs may be stored.

###### Getting Started
Getting Started with Erlang
Categories
Main page
Recent changes
Random page
Help
View source
Editing help