Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find dictionary items whose key matches a substring

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.

like image 294
Abid A Avatar asked May 07 '12 14:05

Abid A


People also ask

How do you check if a dictionary already contains a key?

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().

How do I get a list of key values in a dictionary?

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.

How do you separate a key from a value in a 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.


1 Answers

[value for key, value in programs.items() if 'new york' in key.lower()] 
like image 105
mensi Avatar answered Sep 28 '22 08:09

mensi