473,775 Members | 2,340 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Enumerate and modify a dictionary

Hi all,

I'm trying to do something that should be really easy, but I can't think of an
obvious way to do it. I have a dictionary whose value is a "value type" (as
opposed to a reference type -- in this case, a Boolean):

Dim dic As New Dictionary(Of Int32, Boolean)
dic(123) = True

I want to set all of the existing entries in the dictionary to False. The
obvious solution:

For Each value As Boolean In dic.Values
value = False
Next

does not set the dictionary values to False as one would expect. Rather, this
code gets a temp variable named value and sets that temp variable to false,
leaving the dictionary value unchanged.

Ok, so I try this code:

For Each key As Int32 In dic.Keys
dic(key) = False
Next

That gets me the dreaded "Collection was modified; enumeration operation may not
execute."

So, how can I set all of the Boolean values in this dictionary to False?

TIA - Bob
Jul 1 '08 #1
8 7993
It seems to me that you should just check if the dictionary does not contain
the key, assume false. You should not need to fill the dictionary with
every possibility.

dict.ContainsKe y(123), for example.
"Bob Altman" <rd*@nospam.nos pamwrote in message
news:er******** ******@TK2MSFTN GP04.phx.gbl...
Hi all,

I'm trying to do something that should be really easy, but I can't think
of an obvious way to do it. I have a dictionary whose value is a "value
type" (as opposed to a reference type -- in this case, a Boolean):

Dim dic As New Dictionary(Of Int32, Boolean)
dic(123) = True

I want to set all of the existing entries in the dictionary to False. The
obvious solution:

For Each value As Boolean In dic.Values
value = False
Next

does not set the dictionary values to False as one would expect. Rather,
this code gets a temp variable named value and sets that temp variable to
false, leaving the dictionary value unchanged.

Ok, so I try this code:

For Each key As Int32 In dic.Keys
dic(key) = False
Next

That gets me the dreaded "Collection was modified; enumeration operation
may not execute."

So, how can I set all of the Boolean values in this dictionary to False?

TIA - Bob
Jul 1 '08 #2
Bob,

While we're wating for the elegant solution, here's abrute force solution:

Dim myKeysArray(dic .Keys.Count - 1) As Integer
dic.Keys.CopyTo (myKeysArray, 0)

For Each key As Integer In myKeysArray
dic(key) = False
Next

Kerry Moorman
"Bob Altman" wrote:
Hi all,

I'm trying to do something that should be really easy, but I can't think of an
obvious way to do it. I have a dictionary whose value is a "value type" (as
opposed to a reference type -- in this case, a Boolean):

Dim dic As New Dictionary(Of Int32, Boolean)
dic(123) = True

I want to set all of the existing entries in the dictionary to False. The
obvious solution:

For Each value As Boolean In dic.Values
value = False
Next

does not set the dictionary values to False as one would expect. Rather, this
code gets a temp variable named value and sets that temp variable to false,
leaving the dictionary value unchanged.

Ok, so I try this code:

For Each key As Int32 In dic.Keys
dic(key) = False
Next

That gets me the dreaded "Collection was modified; enumeration operation may not
execute."

So, how can I set all of the Boolean values in this dictionary to False?

TIA - Bob
Jul 1 '08 #3
"Bob Altman" <rd*@nospam.nos pamschrieb
So, how can I set all of the Boolean values in this dictionary to
False?
For Each key In dic.Keys.ToArra y
dic(key) = False
Next

Armin
Jul 1 '08 #4
On 2008-07-01, Bob Altman <rd*@nospam.nos pamwrote:
Hi all,

I'm trying to do something that should be really easy, but I can't think of an
obvious way to do it. I have a dictionary whose value is a "value type" (as
opposed to a reference type -- in this case, a Boolean):

Dim dic As New Dictionary(Of Int32, Boolean)
dic(123) = True

I want to set all of the existing entries in the dictionary to False. The
obvious solution:

For Each value As Boolean In dic.Values
value = False
Next

does not set the dictionary values to False as one would expect.
Just a small comment, since you have received a solution - but, the observed
behavior is EXACTLY what is to be expected... Booleans are value types - and
so on any assignment, a copy is made. It's basically the same as:

Dim b1 As Boolean = True
Dim b2 As Boolean = b1

Console.WriteLi ne ("b1 = {0}, b2={1}", b1, b2)
b1 = False
Console.WriteLi ne ("b1 = {0}, b2={1}", b1, b2)

--
Tom Shelton
Jul 1 '08 #5
While we're waiting for the elegant solution, here's a brute force solution:
>
Dim myKeysArray(dic .Keys.Count - 1) As Integer
dic.Keys.CopyTo (myKeysArray, 0)

For Each key As Integer In myKeysArray
dic(key) = False
Next

Kerry Moorman
Thanks Kerry. I didn't notice that the KeyCollection had a CopyTo function.

I wrote a little app to test the performance of your solution vs. creating a new
Dictionary and populating it with the keys from the old dictionary and values of
False, like this:

' Fabricate a new Dictionary with keys
' from the old Dictionary
Dim newDic As New Dictionary(Of Int32, Boolean)
For Each kvp As KeyValuePair(Of Int32, Boolean) In dic
newDic(kvp.Key) = False
Next

' Replace the old Dictionary with the new one
dic = newDic

It turns out that creating a new dictionary is *much* faster. In my test app
(shown below) I repeat the code that sets the Dictionary entries to False 10,000
times. The algorithm that copies the keys array takes around 700 ms, which the
algorithm that creates a new dictionary only takes about 100 ms. Both
algorithms leave some garbage behind for the GC to collect, and I can't think of
an easy way to measure that part of the performance.

Bob

--- Code ---

Public Class Form1

Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArg s) Handles Button1.Click
' Initialize the Dictionary
Dim dic As New Dictionary(Of Int32, Boolean)

For i As Int32 = 1 To 1000
dic(CInt(Rnd() * 10000)) = True
Next

Dim t1 As DateTime = Now

For i As Int32 = 1 To 10000

' Kerry's algorithm
Dim keys(dic.Count - 1) As Int32
dic.Keys.CopyTo (keys, 0)
For Each key As Int32 In keys
dic(key) = False
Next
Next

Dim t2 As Date = Now
Label1.Text = (t2 - t1).Millisecond s.ToString
End Sub

Private Sub Button2_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArg s) Handles Button2.Click
' Initialize the Dictionary
Dim dic As New Dictionary(Of Int32, Boolean)

For i As Int32 = 1 To 1000
dic(CInt(Rnd() * 10000)) = True
Next

Dim t1 As DateTime = Now

For i As Int32 = 1 To 10000
' Bob's algorithm
Dim newDic As New Dictionary(Of Int32, Boolean)
For Each kvp As KeyValuePair(Of Int32, Boolean) In dic
newDic(kvp.Key) = False
Next

dic = newDic
Next

Dim t2 As Date = Now
Label1.Text = (t2 - t1).Millisecond s.ToString

End Sub
End Class
Jul 1 '08 #6
Bob Altman wrote:
>
I wrote a little app to test the performance of your solution vs.
creating a new Dictionary and populating it with the keys from the
old dictionary and values of False, like this:
(snip)
It turns out that creating a new dictionary is *much* faster. In my
test app (shown below) I repeat the code that sets the Dictionary
entries to False 10,000 times. The algorithm that copies the keys
array takes around 700 ms, which the algorithm that creates a new
dictionary only takes about 100 ms. Both algorithms leave some
garbage behind for the GC to collect, and I can't think of an easy
way to measure that part of the performance.
Label1.Text = (t2 - t1).Millisecond s.ToString
(snip)
Label1.Text = (t2 - t1).Millisecond s.ToString
Whoops! Better make that TotalMillisecon ds, if you want the actual times, not
just the fractional part of a second. :)

On my machine, "Bob's Algorithm" takes about 4 times longer, just over 3
seconds, to complete.

You might be interested in seeing what happens if you create a class to hold
your Boolean, and use objects in the dictionary instead of value types. On my
machine, it beats both methods.

Private Class MyBool
Public TheBool As Boolean
Public Sub New()
TheBool = False
End Sub
Public Sub New(ByVal Init As Boolean)
TheBool = Init
End Sub
End Class

Private Sub Button2_Click(B yVal sender As System.Object, _
ByVal e As System.EventArg s) Handles Button2.Click

Dim dic As New Dictionary(Of Int32, MyBool)

For i As Int32 = 1 To 1000
dic(CInt(Rnd() * 10000)) = New MyBool(True)
Next

Dim t1 As DateTime = Now

For i As Int32 = 1 To 10000
For Each b As MyBool In dic.Values
b.TheBool = False
Next
Next

Dim t2 As Date = Now
Label1.Text = (t2 - t1).TotalMillis econds.ToString

End Sub

Jul 2 '08 #7
> Label1.Text = (t2 - t1).Millisecond s.ToString
>
Whoops! Better make that TotalMillisecon ds, if you want the actual times,
not just the fractional part of a second. :)
Ouch! It's amazing how many ways there are to write subtly wrong code. The
funny part is that it sure seemed to me that it took a lot longer than 1
second to complete (uh, more like 3 seconds)...
On my machine, "Bob's Algorithm" takes about 4 times longer, just over 3
seconds, to complete.

You might be interested in seeing what happens if you create a class to
hold your Boolean, and use objects in the dictionary instead of value
types.
That was actually the first thing I tried, since intuition tells me that it
would be a lot faster to just write to a Boolean field rather than replacing
the entire Dictionary entry. But I gave up when I discovered that I use the
ContainsValue method on the dictionary

If dic.ContainsVal ue(False) Then <do something>

and I didn't want to figure out how to either implement some arcane
interface or write my own "search through the darned thing" routine to get
that to work. But as long as I'm actually doing some performance testing, I
guess I really should try that and see how it compares. (Maybe if I'm lucky
I'll come back tomorrow morning -- it's 10:40 PM in Southern California
right now -- and someone will run that test and post the results.)

Bob

Jul 2 '08 #8
Hi Bob,

Regarding on the performance of the two methods you've considered so far:

1. copy keys to array and modify the original collection

2. not copy keys but directly create a new dictionary

Here are some of my understanding and suggetion:

** For the performance, it depend on what's the critical point of the
execution. For the two approaches here:

1. copy keys approach's critical point is copying all the keys from
dictionary to an key array

2. creating new dictionary's critical point is creating the new dictonary
and also all the objects in it.

Here in your case, the object is simply a boolean value, therefore, I
think the overhead of copying keys into array (in #1 ) will contribute to
the most performance overhead. However, if the stored objects are large
complex class object, I think the creating new dictionary approach will be
overkilled by creating every new objects in the original dictionary.

Therefore, you can decide which approach to use depend on the actual
screnario.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsof t.com.

=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

--------------------
>From: "Bob Altman" <rd*@nospam.nos pam>
References: <er************ **@TK2MSFTNGP04 .phx.gbl>
<A3************ *************** *******@microso ft.com>
>Subject: Re: Enumerate and modify a dictionary
Date: Tue, 1 Jul 2008 16:46:21 -0700
b
>
>While we're waiting for the elegant solution, here's a brute force
solution:
>>
Dim myKeysArray(dic .Keys.Count - 1) As Integer
dic.Keys.CopyTo (myKeysArray, 0)

For Each key As Integer In myKeysArray
dic(key) = False
Next

Kerry Moorman

Thanks Kerry. I didn't notice that the KeyCollection had a CopyTo
function.
>
I wrote a little app to test the performance of your solution vs. creating
a new
>Dictionary and populating it with the keys from the old dictionary and
values of
>False, like this:

' Fabricate a new Dictionary with keys
' from the old Dictionary
Dim newDic As New Dictionary(Of Int32, Boolean)
For Each kvp As KeyValuePair(Of Int32, Boolean) In dic
newDic(kvp.Key) = False
Next

' Replace the old Dictionary with the new one
dic = newDic

It turns out that creating a new dictionary is *much* faster. In my test
app
>(shown below) I repeat the code that sets the Dictionary entries to False
10,000
>times. The algorithm that copies the keys array takes around 700 ms,
which the
>algorithm that creates a new dictionary only takes about 100 ms. Both
algorithms leave some garbage behind for the GC to collect, and I can't
think of
>an easy way to measure that part of the performance.

Bob
Jul 2 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1711
by: David Stockwell | last post by:
Hi Everyone, I'm wondering about the best way to enumerate something. I have a list of columnames for a db and I decided to put them in a giant tuple list for two reasons: 1) its unchangeable 2) I was hoping that creating an enumeration of those names would be easy In the os.stat there is aparrently a list of things you can refer to eg:
4
23480
by: Xah Lee | last post by:
Python has iteritems() and enumerate() to be used in for loops. can anyone tell me what these are by themselves, if anything? are they just for idiom? thanks. Xah xah@xahlee.org http://xahlee.org/PageTwo_dir/more.html
3
2023
by: swingingming | last post by:
On the Order form, I have a subform, OrderDetails, which contains every item one customer orders. After the order is complete, I would like to update the inventory amount. How can I enumerate the records in OrderDetails subform? Thank you. Ming
1
1498
by: Mamatha | last post by:
Hi I have a mutithreading application in VB.NET. In one function i stored some data in dictionaries. i declared global value to store data in dictionaries. Every time dictionary pointer has incremented. for example :public indx as integer dic.additem(indx(i))
5
3209
by: Sandra-24 | last post by:
Is there a way in python to add the items of a dictionary to the local function scope? i.e. var_foo = dict. I don't know how many items are in this dictionary, or what they are until runtime. exec statements are difficult for debuggers to deal with, so as a workaround I built my code into a function and saved it in a .py file. The I load the .py file as a module and call the function instead. This works great, and it has the added...
4
2502
by: CodeLeon | last post by:
I am designing an enhanced GUI suite, and i need to know how to: * Make a user control a "helper" control, ie, one that sits at the bottom (like timer or process) * Make this control modify the behavior of the painted controls already on the form. (ie, make my control handle the painting of the controls on the page) * Make the TextBox contol have it's background painted by me. This seems to be a hassle. Any help would be deeply...
8
1420
by: Dustan | last post by:
Can I make enumerate(myObject) act differently? class A(object): def __getitem__(self, item): if item 0: return self.sequence elif item < 0: return self.sequence elif item == 0: raise IndexError, "Index 0 is not valid."
2
3449
by: =?Utf-8?B?c2lwcHl1Y29ubg==?= | last post by:
Hi I have a class that inherits from Generics Dictionary The string that is used for the key is passed thru-out my pgm and sometimes it has modifiers added to the key string that are used in the system. The problem is now I have to strip the modifer to lookup in the Dictionary and I have to copy this code whenever I need to lookup the key or if more modifers are added
0
2352
by: Jon Slaughter | last post by:
How do I modify the value of a dictionary object? I have something like Dictionary<string, AQ = ... Where A is a struct. I want to change some values in A but
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10267
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10046
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9915
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7463
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6717
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3611
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2852
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.