Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach loop for a complex dictionary is incorrect

I'm using Windows 7 and PowerGUI Script Editor to write a ps1. Here's a part of my codes:

#In global scope
$Type_Trans = "System.Collections.Generic.Dictionary[System.String,PSObject]"
$Type_Farms = "System.Collections.Generic.Dictionary[System.Int32,$Type_Trans]"

$Dic_Counts = New-Object $Type_Farms

#...puts some data in $Dic_Counts here...
#It is no problem with printing out it in console

#Now call the function below
Write-Data $Dic_Counts

Function Write-Data
{
    param(
        $Dic_Counts
    )

    Foreach($Dic_CountsSingle in $Dic_Counts)
    {
        Write-DataSingle $Dic_CountsSingle  #THIS LINE!
    }
}

It's very strange here: why is Dic_CountsSingle not a KeyValuePair, but is just the same as Dic_Counts??

Thank you very much!

like image 792
bychance Avatar asked Mar 23 '12 11:03

bychance


People also ask

Can a for loop be used to iterate over a dictionary?

You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

How to use for loop with dictionary in Python?

In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.

How to use a dictionary in for loop?

This is the simplest way to iterate through a dictionary in Python. Just put it directly into a for loop, and you're done! The preceding code allowed you to get access to the keys ( key ) and the values ( a_dict[key] ) of a_dict at the same time. This way, you can do any operation with both the keys and the values.

How to iterate through dictionary in Python Stack Overflow?

The easiest way to iterate through a dictionary in Python, is to put it directly in a for loop. Python will automatically treat transaction_data as a dictionary and allow you to iterate over its keys.


2 Answers

Use

foreach ($Dic_CountsSingle in $DicCounts.GetEnumerator())

It's the same for hashtables in PowerShell, too, so not particularly surprising.

like image 182
Joey Avatar answered Nov 15 '22 05:11

Joey


I do it like this:

$Dic_Counts.keys | %{ $Dic_Counts[$_]  }
like image 32
manojlds Avatar answered Nov 15 '22 05:11

manojlds