Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Finding a (string) key in a dictionary that contains a substring

In my script I build a dictionary of keys(albums) mapped to artists(values) so that I can do a quick lookup of what artists made what albums. However, I want the user to be able to find all albums which contain a substring. For example a search on "Light" should return

[Light Chasers] = Cloud Cult and also [Night Light] = Au Revoir Simone

What's the best way to do this? Should I even be using a dictionary?

like image 738
Sushisource Avatar asked Jul 15 '10 05:07

Sushisource


People also ask

How do I check if a string contains a substring in Python?

To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring: fullstring = "StackAbuse" substring = "tack" if substring in fullstring: print("Found!")

How do you check if a string is a key in a dictionary Python?

You can check if a key exists in a dictionary using the keys() method and IN operator. What is this? The keys() method will return a list of keys available in the dictionary and IF , IN statement will check if the passed key is available in the list. If the key exists, it returns True else, it returns False .

How do I check if a string is in a dictionary key?

Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.

How do I search for a key in Python?

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.


1 Answers

[(k, v) for (k, v) in D.iteritems() if 'Light' in k]
like image 197
Ignacio Vazquez-Abrams Avatar answered Oct 15 '22 21:10

Ignacio Vazquez-Abrams