Message Boards Message Boards

0
|
4961 Views
|
1 Reply
|
0 Total Likes
View groups...
Share
Share this post:

Lists of Key Values Derived from Key-Value Pairs Using Associations

Posted 10 years ago

I am importing data from a .csv file in the form of 40,000 unique US zip codes, each one matched to one of 200 region codes. My goal is to produce a dictionary of each region code and its linked zip codes. I then want to pass to the dictionary several hundred thousand zip codes to get a list of the appropriate region codes. This seems like a good application of the new function Associations and key-value pairs. Specifically - I want to pass my list of values to get a list of keys. Here is where I am, using abridged and simulated data:

Import the two columns codes and skip the headers in the file

`codes =  Import["filepath"][[1, 3 ;;  ,  ;; 2]];`

This produces a list in the form of: {zip, region} such as this:

`{ {16505, 234}, {16504, 234}, {91521, 456}...}`

I then use the new GroupBy function to produce an Association of key-value pairs:

`groups = GroupBy[codes, Last -> First]`

which produces and Association in the form of:

<| 234 -> {16504, 16505}, 
    456 -> {91521} |>

My next step was to send my list of zip codes using the Position function. Testing with a single zip does return the key value:

In= Position[groups, "16505"]
Out= {{Key[234], 2}}

Which I can Part to get the Key as such:

  In= Position[groups, "16505"][[1, 1]]
    Out= Key[234]

Here is where I am running into trouble. When I submit a list of zip codes I get an unexpected result back:

In= Position[groups, {"16505", "91521"}]
Out= {}

I have tried using other approaches such as the PositionIndex function and Extract. Can anyone suggest a better way to approach this?

POSTED BY: Jon Rogers

The second argument of Position is a pattern to look for

?Position

Position[expr,pattern] gives a list of the positions at which objects matching pattern appear in expr. 
Position[expr,pattern,levelspec] finds only objects that appear on levels specified by levelspec. 
Position[expr,pattern,levelspec,n] gives the positions of the first n objects found. 
Position[pattern] represents an operator form of Position that can be applied to an expression. >>

In your Association the pattern {16505, 91521} does not appear

Note I left out the quotation marks that you had in it since the association you give as an example has lists of integers on the right hand side:

In[1]:=  temp = <| 234 -> {16504, 16505},  456 -> {91521} |>

To get what I think you are after you need to put Alternatives in the second argument of Position, not a list of values, as in

In[2]:= Position[temp, 16504 | 91521]


Out[2]= {{Key[234], 1}, {Key[456], 1}}
POSTED BY: David Reiss
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract