Construct Hash Table from two arrays

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Michael Maher Michael Maher 6 months ago.

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #36921
    Profile photo of Michael Maher
    Michael Maher
    Participant

    Hi Folks,

    I have two distinct arrays which I want to pair up in a hash table. So the first array would represent all the keys in the hash table. The second array the matching values.

    There are 24 items in each list and they are ordered.

    I haven't been able to find any examples of this and I am wondering if it is possible?

    $teams = Invoke-WebRequest -Uri 'http://www.uefa.com/uefaeuro/season=2016/teams/index.html'
    $teamName = ($teams.ParsedHtml.getElementsByTagName('span') | Where{ $_.className -eq 'team-name_name'}).innerText
    

    Sample of returned values . . .

    Albania
    Austria
    Belgium

    $teamURL = ($teams.ParsedHtml.getElementsByTagName('a') | 
      Where{ $_.className -eq 'team-hub_link'}).pathname -replace '//', 'http://www.uefa.com/uefaeuro/'
    $teamID0 = $teamURL -replace '//uefaeuro/season=2016/teams/team=', ''
    $teamID = ($teamID0 -replace '/index.html', '') -replace 'http://www.uefa.com/uefaeuro/uefaeuro/season=2016/teams/team='
    $teamID
    

    Sample of returned values . . .

    2
    8
    13

    Can these values create this table programmatically?

     $table = @{
            'Albania' = '2';
            'Austria' = '8';
            'Belgium' = '13';}
    

    Thanks,

    Michael

    #36923
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Sure. If you're certain the arrays have the same number of elements (and you should probably have code check for that first, just in case), you can just use a for loop:

    $table = @{}
    for ($i = 0; $i -lt $teamName.Count; $i++)
    {
        $table[$teamName[$i]] = $teamID[$i]
    }
    
    #36925
    Profile photo of Michael Maher
    Michael Maher
    Participant

    Thanks Dave, yes that does it.

    I get initializing the empty table and the iteration parameters that follow.

    But looking within the script blocks. It's beautifully simplistic and I would have never thought the hash table variable $table could be manipulated like that.

    Thanks,

    Michael

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.