I have a large dictionary constructed like so:
programs['New York'] = 'some values...' programs['Port Authority of New York'] = 'some values...' programs['New York City'] = 'some values...' ...
How can I return all elements of programs
whose key mentions "new york" (case insensitive)? In the example above, I would want to get all the three items.
EDIT: The dictionary is quite large and expected to get larger over time.
How do you check if a key exists or not in a dictionary? You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key().
The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.
Creating a Dictionary To do that you separate the key-value pairs by a colon(“:”). The keys would need to be of an immutable type, i.e., data-types for which the keys cannot be changed at runtime such as int, string, tuple, etc. The values can be of any type.
[value for key, value in programs.items() if 'new york' in key.lower()]
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