Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the key from a TDictionary?

I have a TDictionary<TKeyClass, TValueClass>.

I want to accomplish something like

for i := 0 to MyDictionary.Count -1 do
  ShowMessage(MyDictionary.Keys[i].AStringProperty)

I cannot Access the Keys anymore I can just use them if I exactly know them.

Is the only alternative create a TDictionary<TValueClass, TKeyValue> ? So I can loop thorugh the Keys?

The workaroud I found is to create a TList<TKeyClass> but this is something i don't like.

like image 874
LaBracca Avatar asked Sep 21 '10 15:09

LaBracca


People also ask

How do you get a key from a dictionary?

Use the keys() function() and apply it to the input dictionary to get the list of all the keys of a dictionary. Print the list of keys of a dictionary by traversing through each key in the above keys list using the list comprehension and for loop.

How do I extract a dictionary key in Python?

Method 1 : Using List. Step 1: Convert dictionary keys and values into lists. Step 2: Find the matching index from value list. Step 3: Use the index to find the appropriate key from key list.

How do I print just the key of a dictionary?

To print the keys and values of the dictionary, use the dict. items() with print() method. To print the dictionary keys, use the dict. keys() with print() method.


1 Answers

Use an enumerator.

for Key in MyDictionary.Keys do
  ShowMessage(Key.AStringProperty);

Since TDictionary is a hash table, you can't access it with integer indexing like an array or TList. But an enumerator works just fine.

like image 94
Mason Wheeler Avatar answered Sep 29 '22 18:09

Mason Wheeler