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!
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.
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.
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.
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.
Use
foreach ($Dic_CountsSingle in $DicCounts.GetEnumerator())
It's the same for hashtables in PowerShell, too, so not particularly surprising.
I do it like this:
$Dic_Counts.keys | %{ $Dic_Counts[$_] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With