I have this:
Dictionary<integer, string> dict = new Dictionary<integer, string>();
I want to select all the items in the dictionary that contain the value abc
.
Is there an inbuilt function that lets me do this easily?
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.
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.
We can use the values() method in Python to retrieve all values from a dictionary. Python's built-in values() method returns a view object that represents a list of dictionaries containing every value. This article explains about the various ways to print all the values of a dictionary in Python.
Well it's reasonably simple with LINQ:
var matches = dict.Where(pair => pair.Value == "abc")
.Select(pair => pair.Key);
Note that this won't be even slightly efficient - it's an O(N)
operation, as it needs to check every entry.
If you need to do this frequently, you may want to consider using another data structure - Dictionary<,>
is specifically designed for fast lookups by key.
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