Reputation: 26067
I need to delete a entry from a list in Python. Here's what it contains:
{'Other': '1.05', 'United States': '93.67', 'Liberia': '3.26', '" alt="" />\n</p>\n</div>': '', 'Canada': '2.02'}
I know I can type:del List_Of_Countries['Canada']
That works perfectly but I am having trouble selecting the one that says " alt="" />\n</p>\n</div>
I think its because of the extra double quote, but I have a few lists that have similar entries so is there an easy way to simply search for the one that either contains "alt" or has " as a value of the key(so I can learn and apply it to other situations)?
Upvotes: 2
Views: 923
Reputation: 515
dpath can solve this.
http://github.com/akesterson/dpath-python
Just setup a filter function that inspects the contents of the strings matching a glob, and pass it to the delete function. So if the stuff you want to delete lives in a dictionary:
$ easy_install dpath
>>> def filter(x):
>>> ... return (str(x) == r'" alt="" />\n</p>\n</div>')
>>> ...
>>> dpath.util.delete(MY_DICT, '*', filter=filter)
.... and that would delete all the objects in the dictionary that matched the string defined in your filter function.
Upvotes: 0
Reputation: 42050
a = {'Other': '1.05', 'United States': '93.67', 'Liberia': '3.26', '" alt="" />\n</p>\n</div>': '', 'Canada': '2.02'}
b = {}
for k, v in a.iteritems():
if v == '' or "alt" in k:
pass
else:
b[k] = v
print b
a non-elegant, but working solution :D
Upvotes: 2
Reputation: 388313
>>> x = {'Other': '1.05', 'United States': '93.67', 'Liberia': '3.26', '" alt="" />\n</p>\n</div>': '', 'Canada': '2.02'}
>>> del x['Canada']
>>> x
{'United States': '93.67', 'Liberia': '3.26', 'Other': '1.05', '" alt="" />\n</p>\n</div>': ''}
>>> del x['" alt="" />\n</p>\n</div>']
>>> x
{'United States': '93.67', 'Liberia': '3.26', 'Other': '1.05'}
Dynamically selecting keys based on some expression is not possible as dictionaries are implemented as hash maps, so the key is hashed internally. As such it is not possible to find a key which consists of something, as the hash would produce something completely else.
The only thing you can do is (obviously) loop through all elements and find the correct ones.
Upvotes: 4