Could someone please tell me, how I can search for only a part of a key in a dictionary (in VB.NET)?
I use the following sample code:
Dim PriceList As New Dictionary(Of String, Double)(System.StringComparer.OrdinalIgnoreCase)
PriceList.Add("Spaghetti alla carbonara", 21.65)
PriceList.Add("Spaghetti aglio e olio", 22.65)
PriceList.Add("Spaghetti alla napoletana", 23.65)
PriceList.Add("Spaghetti alla puttanesca ", 24.65)
PriceList.Add("Spaghetti alla gricia ", 25.65)
PriceList.Add("Spaghetti alle vongole", 26.65)
PriceList.Add("Spaghetti Bolognese", 27.65)
If PriceList.ContainsKey("spaghetti bolognese") Then
Dim price As Double = PriceList.Item("spaghetti bolognese")
Console.WriteLine("Found, price: " & price)
End If
If Not PriceList.ContainsKey("Bolognese") Then
Console.WriteLine("How can I search for only a part of a key?")
End If
If I only know a part of the key like "Bolognese" or just a part of word like "Bolo", how can I search for this part in the complete key?
To simply check if a key exists in a Python dictionary you can use the in operator to search through the dictionary keys like this: pets = {'cats': 1, 'dogs': 2, 'fish': 3} if 'dogs' in pets: print('Dogs found!') # Dogs found! A dictionary can be a convenient data structure for counting the occurrence of items.
By using the dict. get() function, we can easily get the value by given key from the dictionary. This method will check the condition if the key is not found then it will return none value and if it is given then it specified the value.
You can check if there's any entry which a key containing "Bolognese" using Any()
If Not PriceList.Where(Function(x) x.Key.Contains("Bolognese")).Any()
Console.WriteLine("No Bolognese, sorry")
End If
To get a subset of the dictionary with keys containing "Bolognese" only:
Dim subsetOfDictionary = PriceList _
.Where(Function(x) x.Key.Contains("Bolognese")) _
.ToDictionary(Function(x) x.Key, Function(x) x.Value)
To get the list of prices for all entries containing "Bolognese":
Dim pricesForAllThingsBolognese = PriceList _
.Where(Function(x) x.Key.Contains("Bolognese")) _
.Select(Function(x) x.Value) _
.ToList()
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