How do you cross-check a dictionary with a list in Python?
Say I have a list
list: [keith, roger, david], [5, nobody, 31], [attack, thomas, 4]
and a dictionary
dictionary: '55': <Trachea>, 'Roger': <Bert>
I want to delete the items in the dict开发者_JS百科ionary that don't match up with the SECOND part of the list of lists. In this example, I'd want to get rid of '55': but not 'Roger': . Thanks!
#!/usr/bin/python3
# myList = [['keith', 'roger', 'david'], [5, 'nobody', 31], ['attack', 'thomas', 4]]
# myDict = {'55': '...', 'roger': '...'}
secondElements = {x[1] for x in myList}
filteredDict = {k:v for k,v in myDict.items() if (k in secondElements)}
print(filteredDict)
# prints: {'roger': '...'}
There are quicker ways to do it, but making a set secondElements
will accelerate the queries and make it O(1)
time. I edited your list because there were case-sensitivity issues, but you could also use (k.lower() in secondElements)
.
OR:
seconds = set(x[1] for x in d)
dict((k,v) for k,v in dd.iteritems() if k.lower() in seconds)
Edited to not create list each time
nested = [['keith', 'roger', 'david'], [5, 'nobody', 31], ['attack', 'thomas', 4]]
seconds = [row[1] for row in nested]
d = {'55': 'Trachea', 'Roger': 'Bert'}
d = dict(((key, val) for (key, val) in d.items() if key.lower() in seconds))
Create a intermediate set and check against it:
# create set to check against
seconds = set(x[1] for x in list_of_lists)
# remove matching keys
for k in my_dict.keys():
if k not in seconds:
delete my_dict[k]
Easy. Runs in O(N) time, with O(N) storage. Note that in your example, the capitalization will not match ('roger' != 'Roger')
>>> dict_ = {'Roger': 'Bert', 55: 'trachea'}
a=[['keith', 'roger', 'david'], [5, 'nobody', 31], ['attack', 'thomas', 4]]
>>> def delete(x):
... del dict_[x]
>>> map(lambda x: delete(x),filter(lambda x:x not in a[1],dict_))
精彩评论