How to Assign Multiple Values to a Hash Key

How can I assign multiple values to a hash key?

You've created a hash with the symbol name as the key and an array with three elements as the value, so you'll need to iterate through myhash[:name] to get the individual array elements.

C - How to assign multiple values to the same key in a hashmap?

This may not be the best possible solution, but thanks to the above comments I got something working. I am declaring multiple values as pointers to char. Please let me know if I can improve this.

I am yet to implement collision correction.

struct map {        /* creating a map structure */
struct map *next;
char *KEY;
char *value1;
char *value2;
char *value3;
};

I then pass these to the insert function.

struct map *insert(char *KEY, char *value1, char *value2, char *value3) {
/* install: put (name, defn) in */
/* Install uses lookup to determine whether the KEY being installed
is already present. Proceeds to create a new entry or update*/
struct map *np;
unsigned hashval;

if ((np = lookup(KEY)) == NULL) {
np = (struct map *) malloc(sizeof(*np));
if (np == NULL || (np->KEY = strdup(KEY)) == NULL) {
return NULL;
}
hashval = hash(KEY);
np->next = hashtab[hashval];
hashtab[hashval] = np;
}
else {
free((void *)np->value1); //type cast cannot convert from 'Value' to 'Value*'
free((void *)np->value2);
free((void *)np->value3);
}
if ((np->time = strdup(value1)) == NULL) { //map has no field value
return NULL;
}
if ((np->description = strdup(value2)) == NULL) { //map has no field value
return NULL;
}
if ((np->duration = strdup(value3)) == NULL) { //map has no field value
return NULL;
}

return np;
}

Printing these will give the key pointing the the four values.

key1->value1 value2 value3

How can I associate multiple values with a single hash key?

You want a hash of arrays (HoA):

use strict;
use warnings;
use Data::Dump;

my %hash;

while (<DATA>) {
my @fields = split;
push(@{$hash{$fields[0]}}, $fields[1]);
}

dd(\%hash);

__DATA__
CLL s_S616447
CLL s_S612703
MBL s_S599565
MBL s_S577819
UnAff s_S509781
UnAff s_S754982

Output:

{
CLL => ["s_S616447", "s_S612703"],
MBL => ["s_S599565", "s_S577819"],
UnAff => ["s_S509781", "s_S754982"],
}

Adding multiple values to a key in Ruby as well as delete just one value associated

Use a Nil Guard

You need to guard against missing keys and values in your Hash. There are a number of ways to do this, but on any recent Ruby the &. operator ensures that a method doesn't raise an exception if called on nil. The following works fine:

h = {
a: [1, 3, 4],
b: [3, 6],
c: [4, 8, 87]
}

h[:c]&.delete 87; h
#=> {:a=>[1, 3, 4], :b=>[3, 6], :c=>[4, 8]}

h[:x]&.delete 101; h
#=> {:a=>[1, 3, 4], :b=>[3, 6], :c=>[4, 8]}

Hashing multiple values to a key in perl

Basic Perl data structures are about single values. The variable $foo can only store a single value. The array @foo can store an array of single values. The hash %foo has a key that points to a single value.

If you need more (such as a key that points to multiple values), you need to know about Perl References. A Perl reference is a Perl data structure (such as a hash or array) where each entry points not to a single value, but to another structure.

In your case, you'd like your key (the word dgo) to point to an array of words that have those letters.

Imagine something like this:

my @dgo_words = qw(dog dgo god gdo odg ogd);   # All possible combinations
$words{dgo} = \@dgo_words; # The '\' means this is a reference to @dgo_words

Now, words{dgo} points to a reference to the array @dgo_words. If dereference the reference (by putting the correct prefix on the variable), I can get back to the array:

my @array_of_dgo_words = @{ $words{dgo} };

Remember, $words{dgo} points to an array, and putting the @ in front gives me access to that array. The curly braces in this particular case are optional:

my @array_of_dgo_words = @$words{dgo};

Personally, I prefer the braces because it highlights the fact this is a reference. Others feel that eliminating them makes the code easier to read.

If @{ $words{dgo} } is my array, I could use push to add words to the array:

push @{ $words{dgo} }, 'dog';

Now, dog is added to the array referenced by $words{dgo}.

Here's a simple program:

#! /usr/bin/env perl

use strict;
use warnings;
use feature qw(say);

my %words;
#
# First add all the words into the correct key
#
while ( my $word = <DATA> ) {
chomp $word;
my $key = join '', sort split //, $word;
push @{ $words{$key} }, $word;
}

for my $group ( sort keys %words ) { # For each key in my word hash
my @word_group = @{ $words{$group} }; # Dereference to get the list of words
say qq(Words for group "'$group":);
for my $word ( @word_group ) { # This loop prints out the words
say " $word";
}
}

__DATA__
dog
bog
save
god
gob
vase

Access Hash with multiple values ruby

A Hash is a collection of key-value pairs like this: "employee" => "salary". It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index.

The order in which you traverse a hash by either key or value may seem arbitrary and will generally not be in the insertion order. If you attempt to access a hash with a key that does not exist, the method will return nil.

A hash is used to stored large (or small) amounts of data and access it efficiently. For example lets say you have this as a hash:

prices = {
'orange' => 3.15,
'apple' => 2.25,
'pear' => 3.50
}

Now you want to call the keyword apple and get the prices of those items from some users input:

print 'Enter an item to verify price: '
item = gets.chomp

puts "The price of an #{item}: #{prices[item]}"
# <= The price of an apple: 2.25

That's a basic hash, now lets get into what you're doing, using an Array as a key.

prices = {
'apple' => ['Granny Smith', 'Red'],
'orange' => ['Good', 'Not good'],
'pear' => ['Big', 'Small']
}

print 'Enter an item for a list: '
item = gets.chomp

puts "We have the following #{item}'s available: #{prices[item]}"
# <= We have the following apple's available: ["Granny Smith", "Red"]

Now if we wanted to grab one of the types:

puts prices[item][0]
# <= Granny Smith

puts prices[item][1]
#<= Red

Now lets get into more advanced techniques like you are doing above, you're idea is great and all, but what you need to do is append the information into the hash and when you call @name don't try to call it as a symbol:

h = Hash.new{|hsh,key| hsh[key] = [] }
h[@name] = []
#<= []

h[@name] << ['apple', 'pear']
#<= [["apple", "pear"]]
h[@name] << ['orange', 'apple']
#<= [["apple", "pear"], ["orange", "apple"]]

h[@name].flatten[0]
#<= "apple"
h[@name].flatten[1]
#<= "pear"
h[@name].flatten[1, 2]
#<= ["pear", "orange"]

Alright so what did we do?

h = Hash.new{|hsh,key| hsh[key] = [] }

Created a hash with a value as an empty array.

h[@name] = []

Initialized @name to the empty array

h[@name] << ['apple', 'pear']

Appended an array containing apple, pear to the @name key.

h[@name] << ['orange', 'apple']

Appended a second array containing orange, apple to the array, so when we call h[@name][1] right now it will output the first array appended to it.

h[@name].flatten[0]

Flattened the array into a single array and called the first element of the array.

When you call your key (@name) you don't call it as a symbol, because it's already contained inside of a variable. So all you have to do is call that variable and the value for that key will be output successfully. Hopefully this clarifies a few, things, for more information on hashes check this out: http://www.tutorialspoint.com/ruby/ruby_hashes.htm



Related Topics



Leave a reply



Submit