Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Dictionary.Keys.List()[i] correspond to Dictionary.Values.ToList()[i]?

Tags:

c#

dictionary

I have a Dictionary data type. My question is, is Dictionary.Keys.ToList()[i] always correspond to Dictionary.Values.ToList()[i] ? That is, will the following test always passes

public void DictionaryTest(int i, Dictionary<U,T> dict)
{
  var key = dict.Keys.ToList()[i];
  Assert.AreEqual(dict[key], dict.Values.ToList()[i]); 
}
like image 438
Graviton Avatar asked Feb 10 '11 12:02

Graviton


People also ask

How do I get a list of values from a list of keys?

To get the list of dictionary values from the list of keys, use the list comprehension statement [d[key] for key in keys] that iterates over each key in the list of keys and puts the associated value d[key] into the newly-created list.

How do I get all the values of a key in Python?

In Python to get all key-values pair from the dictionary, we can easily use the method dict. items(). This method helps the user to extract all keys and values from the dictionary and iterate the object with a for loop method.

Do dictionary keys have to be strings?

The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.


2 Answers

I would say yes based on this from MSDN:

The order of the values in the Dictionary.ValueCollection is unspecified, but it is the same order as the associated keys in the Dictionary.KeyCollection returned by the Keys property.

like image 129
SwDevMan81 Avatar answered Oct 07 '22 06:10

SwDevMan81


Checking the MSDN entry for Dictionary.Keys Property:

The order of the keys in the Dictionary.KeyCollection is unspecified, but it is the same order as the associated values in the Dictionary.ValueCollection returned by the Values property.

like image 32
CodesInChaos Avatar answered Oct 07 '22 06:10

CodesInChaos